Flask Request and Response
The core of a web application is "receive requests, return responses"; this chapter comprehensively explains how to read request data and build various types of responses in Flask.
All examples can be run and verified directly in the development server.
The request object—request
Flask provides all request information through the global proxy object request.
Although it is a "global" object, Flask internally uses thread isolation to ensure that each request gets its own data.
Example
Import request, a thread-safe proxy object
from
flask
import
Flask
,
request
app
=
Flask
(
name
)
@
app.
route
(
"/debug"
)
def
debug
(
)
:
Output various information about the request to help understand the request object
return
f
"""
Request debugging information
- Method: {request.method}
- Path: {request.path}
- Full URL: {request.url}
- Host: {request.host}
- Client IP: {request.remote_addr}
- User-Agent:{request.headers.get('User-Agent')}
"""
Visit http://127.0.0.1:5000/debug?foo=bar to see the detailed request information.

Getting query parameters—request.args
The parameters after ? in a URL are called query parameters (Query String).
Read using request.args, which is like a dictionary:
Example
@
app.
route
(
"/search"
)
def
search
(
)
:
request.args.get() safely gets a parameter, returning None when the key does not exist
keyword
=
request.
args
.
get
(
"keyword"
,
""
)
Get the query keyword
page
=
request.
args
.
get
(
"page"
,
"1"
)
Get the page number, defaulting to 1
return
f
"""
Search results
Keyword: {keyword}
Page: {page}
"""
Test: /search?keyword=flask&page=2
Test: /search?keyword=RUNOOB
it is recommended to use .get() the method rather than direct index access request.args["key"], because the latter raises when the key does not exist KeyError, resulting in a 400 error page.
Getting form data—request.form
To handle form data submitted by a POST request, use request.form:
Example
@
app.
route
(
"/register"
,
methods
=
[
"GET"
,
"POST"
]
)
def
register
(
)
:
if
request.
method
==
"POST"
:
Use the value of the name="username" field in the form
username
=
request.
form
.
get
(
"username"
,
""
)
password
=
request.
form
.
get
(
"password"
,
""
)
if
not
username
or
not
password:
return
"
Error
Username and password cannot be empty
",
400
return
f
"
Registration successful
Welcome {username} to RUNOOB!
"
Show the registration form on a GET request
return
"""
Registration
"""
Note: In the HTML page that handles the form, Must be set method="post", otherwise the data will be sent via the URL's query string (GET method), and sensitive information will be exposed in the URL.
Getting JSON data—request.json
In modern web development, JSON is the most common data format.
When a client sends a request with Content-Type: application/json, use request.json to get the parsed data:
Example
@
app.
post
(
"/api/user"
)
def
create_user
(
)
:
request.json returns JSON data already parsed into a Python dict
data
=
request.
json
For example, the client sends {"name": "runoob", "email": "test@runoob.com"}
Safely get a field
name
=
data.
get
(
"name"
,
"File %s type is: %s%n"
)
=
data.
get
(
"email"
,
"Not provided"
)
Return the dict directly, and Flask automatically converts it to a JSON response
return
{
"message"
:
"User created successfully"
,
"name"
: name
,
"email"
:
}
You can test with curl or Postman:
$ curl -X POST http://127.0.0.1:5000/api/user \
-H "Content-Type: application/json" \
-d '{"name": "runoob", "email": "test@runoob.com"}'
{
"message": "用户创建成功",
"name": "runoob",
"email": "test@runoob.com"
}
File upload
To handle uploaded files, use request.files together with the secure_filename() provided by Werkzeug to ensure filename safety:
Example
import
os
from
werkzeug.
utils
import
secure_filename
Filter out dangerous filename characters
Configure the upload directory (in real projects, read from configuration)
UPLOAD_DIR
=
"uploads"
@
app.
route
(
"/upload"
,
methods
=
[
"GET"
,
"POST"
]
)
def
upload_file
(
)
:
if
request.
method
==
"POST"
:
Check whether a file has been uploaded
if
"file"
not
in
request.
files
:
return
"No file selected"
,
400
file
=
request.
files
[
"file"
]
The user may have submitted an empty form (no file selected)
if
file
.
filename
==
""
:
return
"Filename is empty"
,
400
secure_filename filters out dangerous characters such as path traversal
For example, "../../etc/passwd" is processed as "etc_passwd"
filename
=
secure_filename
(
file
.
filename
)
Ensure the upload directory exists
os
.
makedirs
(
UPLOAD_DIR
,
exist_ok
=
True
)
Save file
file
.
save
(
os
.
path
.
join
(
UPLOAD_DIR
,
filename
)
)
return
f
"File {filename} uploaded successfully"
Show the upload form on a GET request
return
"""
Upload files
"""
If the form has a file upload field, the tag must be set to enctype="multipart/form-data", otherwise the file data will not be sent by the browser.
Complete guide to response types
A view function can return data of many types, and Flask automatically converts them into appropriate HTTP responses.
Understanding this conversion rule is the key to mastering Flask.
Return the string
The returned string is used as the HTML response body, with a default status code of 200 and Content-Type of text/html.
Returning a dict or list (JSON)
jsonify() is automatically called to convert it to a JSON response, with Content-Type of application/json.
Example
@
app.
get
(
"/api/posts"
)
def
get_posts
(
)
:
Return a dict, and Flask automatically converts it to JSON
return
{
"status"
:
"ok"
,
"data"
:
[
{
"id"
:
1
,
"title"
:
"Flask Getting Started Tutorial"
}
,
{
"id"
:
2
,
"title"
:
"RESTful API design"
}
,
]
}
@
app.
get
(
"/api/tags"
)
def
get_tags
(
)
:
Return a list, and Flask automatically converts it to JSON
return
[
"Python"
,
"Flask"
,
"Web development"
,
"RUNOOB"
]
Returning a tuple—controlling the status code and response headers
The tuple format is very useful and has three forms:
Example
Form 1: (body, status_code)
@
app.
get
(
"/not-found"
)
def
not_found
(
)
:
return
"
Page not found
",
404
Form 2: (body, headers_dict)
@
app.
get
(
"/custom-header"
)
def
custom_header
(
)
:
return
"OK"
,
{
"X-Custom-Header"
:
"runoob"
}
Form 3: (body, status_code, headers_dict)
@
app.
post
(
"/api/login"
)
def
api_login
(
)
:
Return a token and a custom status code
return
{
"token"
:
"abc123"
,
"user"
:
"runoob"
}
,
201
,
{
"X-RateLimit"
:
"100"
}
Redirection
Use the redirect() function to guide the user to another URL:
Example
from
flask
import
Flask
,
redirect
,
url_for
app
=
Flask
(
name
)
@
app.
route
(
"/"
)
def
index
(
)
:
Redirect to the login page when visiting the homepage
return
redirect
(
url_for
(
"login"
)
)
@
app.
route
(
"/login"
)
def
login
(
)
:
return
"
Please log in first
"@
app.
route
(
"/old-page"
)
def
old_page
(
)
:
For permanent migration from an old page to a new one, use the 301 status code
return
redirect
(
url_for
(
"new_page"
)
,
code
=
301
)
@
app.
route
(
"/new-page"
)
def
new_page
(
)
:
return
"
This is the new page
"The default redirect status code is 303 See Other, suitable for redirects after form submission (PRG pattern).
For permanent migration scenarios, use code=301.
Terminating a request—abort
Use abort() to immediately terminate the current request and return an HTTP error:
Example
from
flask
import
abort
@
app.
route
(
"/post/int:post_id"
)
def
view_post
(
post_id
)
:
Assume the article ID is only 1-100
if
post_id
<
1
or
post_id
100:
Immediately return 404, and subsequent code will not execute
abort
(
404
)
return
f
"
Article #{post_id}
"@
app.
route
(
"/admin"
)
def
admin
(
)
:
Return 403 for unauthorized access
abort
(
403
,
description
=
"You do not have permission to access this page"
)
make_response—manually controlling the response
When you need to manually set cookies or customize response headers, use make_response():
Example
from
flask
import
make_response
@
app.
route
(
"/set-cookie"
)
def
set_cookie
(
)
:
make_response wraps the view function's return value into a Response object
resp
=
make_response
(
"
Cookie set
")
Set a cookie on the Response object
resp.
set_cookie
(
"theme"
,
"dark"
,
max_age
=
60
60
24
)
Valid for 24 hours
resp.
set_cookie
(
"lang"
,
"zh-CN"
)
You can also customize response headers
resp.
headers
[
"X-Powered-By"
]
=
"RUNOOB-Flask"
return
resp
request common attributes quick reference
| property | Type | Description | Example value |
|---|---|---|---|
| request.method | str | HTTP Request Methods | "GET", "POST" |
| request.path | str | URL path (excluding the domain) | "/search" |
| request.args | MultiDict | URL query parameter | ?keyword=flask&page=1 |
| request.form | MultiDict | POST form data | username=admin |
| request.json | dict or None | JSON request body (parsed) | {"name": "runoob"} |
| request.files | FileMultiDict | Uploaded files | request.files["avatar"] |
| request.headers | Headers | Request headers | request.headers["User-Agent"] |
| request.cookies | dict | Cookies sent by the client | request.cookies.get("theme") |
| request.remote_addr | str | Client IP address | "127.0.0.1" |