Question

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)
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top