Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting to Flask with Postman versus requests populates different request attributes

I'm sending a POST request to my Flask app with Postman and also the requests library. When I use Postman, I can get the data with json.loads(request.data). When I use requests or curl, I can get the data with request.form. Why does sending the same data with the two tools populating different attributes?

like image 314
PythonEnthusiast Avatar asked May 09 '15 19:05

PythonEnthusiast


1 Answers

You've used Postman to send the data as JSON, and you've used requests and curl to send it as form data. You can tell either program to send the data as whatever you expect, rather than letting it use its "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 the JSON directly from the Flask request, without loading it yourself:

from flask import request
data = request.get_json()

request.data holds the body of the request, whatever format it may be. 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 the parsed data. If it was json, then request.get_json() will access it instead.


If you're really not sure if you'll get the data as a form or as JSON, you could write a short function to try to use one and if that doesn't work use the other.

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()
like image 155
davidism Avatar answered Sep 23 '22 19:09

davidism