-1

I am trying to get json data from webapp :

I tried:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
    print (request.is_json)
    content = request.get_json()
    print (content)
    return 'JSON posted'

app.run(port= 8090)

and then:

import requests

url='http://127.0.0.1:8090/postjson'

hj=requests.post(url,{
 "device":"TemperatureSensor",
 "value":"20",
 "timestamp":"25/01/2017 10:10:05"
})

print(hj.text)

and i am getting:

on server side:

 * Running on http://127.0.0.1:8090/ (Press CTRL+C to quit)
127.0.0.1 - - [22/Apr/2018 01:45:54] "POST /postjson/ HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:46:01] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:46:01] "GET /robots.txt HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:51:46] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:51:47] "GET /robots.txt HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:52:26] "GET /postjson' HTTP/1.1" 404 -
127.0.0.1 - - [22/Apr/2018 01:52:48] "GET /postjson/ HTTP/1.1" 404 -

and client output:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>

I just want to post json and receive and save it to a variable at server side

davidism
  • 121,510
  • 29
  • 395
  • 339
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
  • 2
    I am not able to reproduce your problem. The code works for me. But one thing you should do (though it will probably not solve your 404 issue) is put `json=` before the dictionary in your requests call. Other than that I suggest stopping the server, verifying that the connection fails when running the client script, restarting the server, and trying again. By the way why are there logs for `/` and `/robots.txt`? – Alex Hall Apr 21 '18 at 20:50
  • @AlexHall can you show me a little example like how i can send json via url in flask and then receive it on server side ? – Aaditya Ura Apr 21 '18 at 20:57
  • I was saying you should write `requests.post(url, json={...})`, but the missing `json=` doesn't explain your 404 error and otherwise your code is perfect. – Alex Hall Apr 21 '18 at 21:02

1 Answers1

0

There is only one issue in you post script . your need to set parameter in request.post call i.e i.e hj=requests.post(url,json='some json')
it can also be seen from requests.post function definition def post(url, data=None, json=None, **kwargs): so in your case you were sending it as data not as json.

import requests

url='http://127.0.0.1:8090/postjson'

hj=requests.post(url,json = {
 "device":"TemperatureSensor",
 "value":"20",
 "timestamp":"25/01/2017 10:10:05"
})

print(hj.text)
toheedNiaz
  • 1,435
  • 1
  • 10
  • 14