Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask / Werkzeug request objects form parameter

I have an Flask app that serves an API to a Django consumer. I use the requests library in my consumer to hit the API.

My problem is this: When I test my API I get POST data in request.form, and when I hit it from my consumer (using requests library) I get POST data in request.data.

E.g.,

API endpoint in Flask app:

@mod.route('/customers/', methods=['POST'])
def create_prospect():
    customer = Customer()
    prospect = customer.create_prospect(request.form)
    return jsonify(prospect.serialize()), 201

Testing API endpoint in Flask app:

def test_creating_prospect(self):
    with self.app.app_context():
        data = {'name': 'Test company and co'}
        response = self.client.post(self.url, data=data)
        ...

This populates request.form in my endpoint, which works fine.

Consuming the API from my Django app, using requests:

...
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data = {'name': 'Test company and co'}
response = requests.post(url, data=data, headers=headers)

This populates request.data in my endpoint, which fails as I'm checking request.form for the info.

I've had a thought while writing this question; Maybe the json headers are making request.data be populated instead of request.form?

Any input appreciated.

Edit - I tried adding the headers to my test, worked fine:

    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    response = self.client.post(self.url, data=data, headers=headers)
like image 639
Chris McKinnel Avatar asked Jun 17 '13 03:06

Chris McKinnel


People also ask

How do you request parameters on a Flask?

args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters. And finally, we need to replace <argument name> with the argument/variable we want the value of.

How do you request objects in Flask?

The data from a client's web page is sent to the server as a global request object. In order to process the request data, it should be imported from the Flask module. Form − It is a dictionary object containing key and value pairs of form parameters and their values.

What is request Get_json ()?

Request. get_json (force=False, silent=False, cache=True)[source] Parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.


1 Answers

Ah, I was sending an incorrect Content-Type. Changing it to 'application/x-www-form-urlencoded' makes request.form get the right stuff.

request.data is populated with stuff Flask/Werkzeug doesn't know what to do with according to the docs.

like image 183
Chris McKinnel Avatar answered Sep 22 '22 17:09

Chris McKinnel