python - Flask: Cannot Decode Incoming JSON Submitted Using Requests -
i'm having issue trying decode python dictionary sent server json. have in application:
payload = {'status':[bathroomid,item,percentage,timestamp]} r=requests.post(url,none,json.dumps(payload))
here in flask server:
req = request.get_json() print req['status']
when try print content of req['status']
, seems python won't recognize dictionary , internal server error.
i tried printing req
, , none
what missing?
unless set content-type
header application/json
in request, flask not attempt decode json found in request body.
instead, get_json
return none
(which you're seeing right now).
so, need set content-type
header in request.
fortunately since version 2.4.2 (released year ago), requests has helper argument post json; set proper headers you. use:
requests.post(url, json=payload)
alternatively (e.g. using requests < 2.4.2), can set header yourself:
requests.post(url, data=json.dumps(payload), headers={"content-type": "application/json"})
here relevant code flask:
- flask only loads json if
is_json
true
(or if passforce=true
get_json
). otherwise, returnsnone
. is_json
looks @content-type
header, , looksapplication/json
there.
Comments
Post a Comment