Handling HTTP Requests
There is a flask's Request class that very helps to handle users' requests. You have to import just a request from flask.
1 | |
By writing . after request you will see all methods and attributes of the request object in your editor:
flask.request
-
request.dataContains the incoming request data as a string in case it came with a mime-type Flask does not handle. -
request.args- the key/value pairs in the URL query string request.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 theapplication/jsoncontent type, or userequest.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.
Let's try this!
- Create
form.htmlon yourtemplates/dir - Create one view function that returns only HTML form.
- Then, we will create a view function for handling simple POST requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
action- endpoint that we want to send requestmethod- We will use HTTP POST for sending something.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
Only HTTP
POSTmethods are allowed in thesubmitview.
| It works 😁🎉 |
This is the end of our simple flask basics tutorial 😊