How to access data from a Flask request
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.
Overview of HTTP requests
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: The
GETmethod requests data from a server. - POST: The
POSTmethod is used to submit data to be processed by the server. - PUT: The
PUTmethod updates an existing resource on the server. - DELETE: The
DELETEmethod removes a resource from the server.
Installations
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
Access data in Flask request
Data can be accessed in the following ways from a Flask request. Let’s discuss them one by one:
1. Accessing the form data
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')
2. Returning the JSON data
To return the JSON data in a Flask route, you can use the jsonify() function provided by Flask.
jsonify(data)
3. Accessing query string
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')
4. Returning the Dictionary Cookies
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')
Code example
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.
Output
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 theset_cookies()function. -
/get-cookies: It will show the data we stored in theset_cookies()function.
Sample output
This output is for the route /form :
Code explanation
-
Lines 1–4: This section imports essential modules—
Flaskfor app creation,render_templatefor HTML rendering,requestfor request data access,redirectfor URL redirection,jsonifyfor JSON responses,url_forfor URL generation, andmake_responsefor custom HTTP responses. It initializes a Flask server namedapp. -
Lines 9–17: This section defines a Flask route at
/formthat handlesGETandPOSTrequests.- On a
GETrequest, it renders an HTML template calledform.htmland passes the data list to it. - A
POSTrequest retrieves the values of thenameandagefields from the form data usingrequest.form.get(). It then appends this data to thedatalist.
- On a
-
Lines 20–24: A function is marked for the
/queryroute, processing query parameters likenameandageusingrequest.args.get(). It then forms a response with these values. -
Lines 27–34: The function is annotated for the
/jsonroute. A sample data dictionary,data, is generated. Subsequently, thejsonify()function transforms thedatadictionary into aJSONresponse. -
Lines 37–43: A function is associated with the route
/set-cookies. It involves creating a response object usingmake_response()and initializing it with the message Cookies have been set! Then, theresponseobject’sset_cookie()method sets two cookies,usernameanduser_id, with corresponding values. -
Lines 46–52: The function is linked to the
/get-cookiesroute. It employsrequest.cookies.get()to retrieve theusernameanduser_idcookies from the client. This data is structured into acookies_dictdictionary 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 to3000.
Test yourself
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
Free Resources