Posting to Flask with Postman Messages and Queries Fills Various Query Attributes

I am sending a POST request to my Flask application with Postman, as well as a request library. When I use Postman, I can get the data using json.loads(request.data) . When I use queries or curls, I can get data using request.form . Why sending the same data with two tools filling different attributes?

+5
source share
2 answers

You used Postman to send data as JSON, and you used requests and curls to send it as form data. You can tell any program to send the data as you expect, instead of letting it use it by default. For example, you can send JSON with requests:

 import requests requests.post('http://example.com/', json={'hello': 'world'}) 

Also note that you can get JSON directly from a Flask request without loading it yourself:

 from flask import request data = request.get_json() 

request.data contains the body of the request, regardless of its format. Common types are application/json and application/x-www-form-urlencoded . If the content type was form-urlencoded , then request.form will be populated with parsed data. If it was json , then request.get_json() will access it.


If you are really not sure whether you will receive the data as a form or as JSON, you can write a short function to try to use it, and if that does not work, use another.

 def form_or_json(): data = request.get_json(silent=True) return data if data is not None else request.form # in a view data = form_or_json() 
+8
source

I hope this quote from http://werkzeug.pocoo.org/docs/0.10/wrappers/#werkzeug.wrappers.Request explains this:

<strong> data A descriptor that calls get_data () and set_data (). This should not be used and will eventually be obsolete.

-1
source

All Articles