-1

i have this code on server side

from flask import Flask, request, jsonify

app=Flask(__name__)

@app.route("/pingtest")
def pingtest():
    return "Pong!"

@app.route("/registrar_alumno", methods=["POST"])
def registrar_alumno():
    print(request.json)
    return jsonify(request.json)

app.run(debug=True,port=4000)

and on the client i have this code

import requests

r=requests.post("http://127.0.0.1:4000/registrar_alumno",
    data={"test":"hello there"})
print(r.text)

i expect to obtain {"test":"hello there"} in both sides but i have this on server:

(asistencias) PS C:\Users\Alumno\Desktop\Proyectos\py\gestion_academica\asistencias> python .\server.py [...] (irrelevants messages that server always shows)

None #...(this should be print(request.json) instruction)

127.0.0.1 - - [15/Mar/2020 16:22:45] "←[37mPOST /registrar_alumno HTTP/1.1←[0m" 200 -

and this on client

(asistencias) PS C:\Users\Alumno\Desktop\Proyectos\py\gestion_academica\asistencias> python .\testclient.py

None

i have no idea what's wrong with this, i hope someone can help me to found the bug

Community
  • 1
  • 1
  • sorry in the client below a obtain "null" instead of None – Jose facundo Bogado Mar 15 '20 at 20:01
  • i tried on client requests.post function: headers={"Content-Type":"application/json"} but now i have an error:

    Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

    – Jose facundo Bogado Mar 15 '20 at 20:10
  • The formatting on this makes it kind of hard to read. Can you post more of the response from client and server and format with ```?. Also, your POST request did generate a 200 (successful response)? – meatspace Mar 15 '20 at 20:35
  • @JosefacundoBogado, you cannot just pass the header, the data needs to be encoded properly. Use the `json` parameter instead of `data`. – atwalsh Mar 15 '20 at 20:38
  • thanks, i know this is a foolish question but for some reason i dont notice this when a have read the requests´s docs – Jose facundo Bogado Mar 22 '20 at 07:49
  • i supossed that if i want to use data instead of json ¿i should use request.form attribute in server side? – Jose facundo Bogado Mar 22 '20 at 07:54

1 Answers1

0

This is happening because you are using the data parameter with a dictionary in your client request which sends form-encoded data, causing request.json to return None.

Use the json parameter to send JSON:

import requests

r=requests.post("http://127.0.0.1:4000/registrar_alumno", json={"test":"hello there"})

This will serialize the data as JSON and change the Content-Type header to application/json.

See the requests docs on more complicated POST requests.

davidism
  • 121,510
  • 29
  • 395
  • 339
atwalsh
  • 3,622
  • 1
  • 19
  • 38
  • hi, thats great, i found another solution, not so good idea, i put data=json.dumps({dict}) and it works too, but your answer is clearly the most properly – Jose facundo Bogado Mar 22 '20 at 07:46