I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data?
from flask import request @app.route('/', methods=['GET', 'POST']) def parse_request(): data = request.data # data is empty # need posted data here The answer to this question led me to ask Get raw POST body in Python Flask regardless of Content-Type header next, which is about getting the raw data rather than the parsed data.
By default, the Flask route responds to GET requests. However, you can change this preference by providing method parameters for the route () decorator. To demonstrate the use of a POST method in a URL route, first let us create an HTML form and use the POST method to send form data to the URL.
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.
The docs describe the attributes available on the request object (from flask import request) during a request. In most common cases request.data will be empty because it's used as a fallback:
request.dataContains the incoming request data as string in case it came with a mimetype Flask does not handle.
request.args: the key/value pairs in the URL query stringrequest.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.request.values: combined args and form, preferring args if keys overlaprequest.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.All of these are MultiDict instances (except for json). You can access values using:
request.form['name']: use indexing if you know the key existsrequest.form.get('name'): use get if the key might not existrequest.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With