Flask is a robust Python web framework that allows us to build web applications and APIs. One of the key tasks in web development is processing incoming data from clients, and Flask makes it easier to access and manipulate this data.
To learn about the basics of Flask, we can refer to the following Answer: Learn Flask in five minutes.
HTTP methods are standardized ways for clients to communicate their intentions to servers when interacting with resources on the web.
Here’s some commonly used HTTP methods:
GET
method requests data from a server.POST
method is used to submit data to be processed by the server.PUT
method updates an existing resource on the server.DELETE
method removes a resource from the server.To get the data received in a Flask request, we have a Python package called requests
.
pip install requests
In addition to that, a Flask
server will also be needed:
pip install Flask
Data can be accessed in the following ways from a Flask request. Let’s discuss them one by one:
When dealing with form data sent via a POST
request, we can use the request.form
object to access the data. This is commonly used when processing HTML forms.
request.form.get('value')
To return the JSON data in a Flask route, you can use the jsonify()
function provided by Flask.
jsonify(data)
Using the request
object, we can access the query string parameters from the URL
. The query string parameters are the key-value pairs after a URL’s question mark ().
request.args.get('name')
In Flask, you can manage cookies and return JSON
data as responses to client requests.
To set the cookies:
response = make_response("text")
response.set_cookie('key', 'value')
To get the cookies:
request.cookies.get('key')
Let’s create a simple Flask server that demonstrates working with all these ways to access data from a request.
<!DOCTYPE html> <html> <head> <title>Form Example</title> </head> <body> <h1>Form Example</h1> <h2>Submit Data:</h2> <form method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <br> <label for="age">Age:</label> <input type="number" id="age" name="age" required> <br> <button type="submit">Submit</button> </form> <h2>Submitted Data:</h2> <ul> {% for item in data %} <li>{{ item.name }}, {{ item.age }}</li> {% endfor %} </ul> </body> </html>
The render_template() function is a built-in feature in Flask that allows you to render and display HTML templates within your application. It’s particularly useful for generating dynamic web pages by injecting data into templates.
The app has five routes, /form
, /json
, /query
, /set-cookies
, and /get-cookies
. Let’s look at the working and output of all of them. Navigate to the app link (given under the code widget) and append the following routes to the URL:
/form
: A form will appear. Enter your name and age in it, and the data will be updated.
/json
: The JSON data passed in the function will be rendered.
/query
: A sample text Hello, None! Your age is None will be rendered. Append this ahead of the /query
: ?name=User&age=23
. Now, see the output. It will render the name and age in the query string.
/set-cookies
: It will set the cookie data as given in the set_cookies()
function.
/get-cookies
: It will show the data we stored in the set_cookies()
function.
This output is for the route /form
:
Lines 1–4: This section imports essential modules— Flask
for app creation, render_template
for HTML rendering, request
for request data access, redirect
for URL redirection, jsonify
for JSON responses, url_for
for URL generation, and make_response
for custom HTTP responses. It initializes a Flask server named app
.
Lines 9–17: This section defines a Flask route at /form
that handles GET
and POST
requests.
GET
request, it renders an HTML template called form.html
and passes the data list to it.POST
request retrieves the values of the name
and age
fields from the form data using request.form.get()
. It then appends this data to the data
list.Lines 20–24: A function is marked for the /query
route, processing query parameters like name
and age
using request.args.get()
. It then forms a response with these values.
Lines 27–34: The function is annotated for the /json
route. A sample data dictionary, data
, is generated. Subsequently, the jsonify()
function transforms the data
dictionary into a JSON
response.
Lines 37–43: A function is associated with the route /set-cookies
. It involves creating a response object using make_response()
and initializing it with the message Cookies have been set! Then, the response
object’s set_cookie()
method sets two cookies, username
and user_id
, with corresponding values.
Lines 46–52: The function is linked to the /get-cookies
route. It employs request.cookies.get()
to retrieve the username
and user_id
cookies from the client. This data is structured into a cookies_dict
dictionary and returned.
Lines 55–56: This section runs the Flask application, enabling debugging mode, specifying the host as 0.0.0.0
, and setting the port to 3000
.
Let’s take a moment to ensure you have correctly understood how to get the data in the Flask request. The quiz below helps you check if you have understood the concepts:
Requests in Flask
Which request type is used to update an existing resource on a server?
GET
POST
PUT
DELETE