Flask View Functions
A view function is a core part of a Flask application; it is responsible for handling requests and generating responses.
View functions are closely tied to routes, which map URLs to specific view functions.
The following is a detailed explanation of Flask view functions, including how to define them, use request data, return responses, and handle errors.
- Defining a view function: A view function is the core functionality that handles requests and returns responses.
- Receive request data: When using
requestobject to obtain URL parameters, form data, query parameters, and so on. - Return the response: Can return a string, HTML, JSON, or a custom response object.
- Handling requests and responses: When using
requestobject andmake_responseto handle requests and generate custom responses. - Handling errors: Handle exceptions within the view function or use Flask's error-handling mechanism.
- View function decorators: When using
@app.before_request、@app.after_requestand other decorators to handle logic before and after requests. - Status codes returned by view functions: You can specify an HTTP status code to indicate the result of request processing.
1. Defining a view function
A view function is an ordinary Python function that receives a request and returns a response. View functions are usually used together with routes, mapping URLs to view functions via decorators.
Example
from
flask
import
Flask
app
=
Flask
(
name
)
@
app.
route
(
'/'
)
def
home
(
)
:
return
'Hello, World!'
@app.route('/'): Map the root URL/tohomeview function.def home(): A view function that returns a string'Hello, World!'as the response.
2. Receiving request data
A view function can receive different types of request data, including URL parameters, form data, query parameters, and so on.
Getting URL parameters:
Example
@
app.
route
(
'/greet/
)
def
greet
(
name
)
:
return
f
'Hello, {name}!'
is a URL parameter passed to the view functiongreet。
Getting form data:
Example
from
flask
import
request
@
app.
route
(
'/submit'
,
methods
=
[
'POST'
]
)
def
submit
(
)
:
username
=
request.
form
.
get
(
'username'
)
return
f
'Form submitted by {username}!'
request.form.get('username'): gets the username field from form data in a POST request.
Getting query parameters:
Example
@
app.
route
(
'/search'
)
def
search
(
)
:
query
=
request.
args
.
get
(
'query'
)
return
f
'Search results for: {query}'
request.args.get('query'): Gets the query parameter query from a GET request.
3. Returning a response
A view function can return several types of responses, including a string, HTML, JSON, or a custom response object.
Returning a string:
Example
@
app.
route
(
'/message'
)
def
message
(
)
:
return
'This is a simple message.'
Returning an HTML template:
Example
from
flask
import
render_template
@
app.
route
(
'/hello/
)
def
hello
(
name
)
:
return
render_template
(
'hello.html'
,
name
=
name
)
render_template('hello.html', name=name): Renders the HTML template hello.html and passes the name variable to the template.
Returning JSON data:
Example
from
flask
import
jsonify
@
app.
route
(
'/api/data'
)
def
api_data
(
)
:
data
=
{
'key'
:
'value'
}
return
jsonify
(
data
)
jsonify(data): Converts a Python dictionary into a JSON response.
Returning a custom response object:
Example
from
flask
import
Response
@
app.
route
(
'/custom'
)
def
custom_response
(
)
:
response
=
Response
(
'Custom response with headers'
,
status
=
200
)
response.
headers
[
'X-Custom-Header'
]
=
'Value'
return
response
Response('Custom response with headers', status=200): Creates a custom response object and sets the response headers.
4. Handling requests and responses
A view function can access the request object and generate a response based on the request data. You can use the request object to get information about the request and make_response to create a custom response.
Using the request object:
Example
from
flask
import
request
@
app.
route
(
'/info'
)
def
info
(
)
:
user_agent
=
request.
headers
.
get
(
'User-Agent'
)
return
f
'Your user agent is {user_agent}'
request.headers.get('User-Agent'): Gets the User-Agent information from the request headers.
Using make_response:
Example
from
flask
import
make_response
@
app.
route
(
'/header'
)
def
custom_header
(
)
:
response
=
make_response
(
'Response with custom header'
)
response.
headers
[
'X-Custom-Header'
]
=
'Value'
return
response
make_response('Response with custom header'): Creates a response object and sets custom header information.
5. Handling errors
You can handle exceptions or errors within a view function, or use the error-handling mechanism provided by Flask to handle errors in the application.
Handling errors in a view function:
Example
@
app.
route
(
)
def
divide
(
x
,
y
)
:
try
:
result
=
x / y
return
f
'Result: {result}'
except
ZeroDivisionError
:
return
'Error: Division by zero'
,
400
Use a try-except statement to handle a division-by-zero error and return a custom error message and status code.
Global error handling:
Example
@
app.
errorhandler
(
404
)
def
not_found
(
error
)
:
return
'Page not found'
,
404
@app.errorhandler(404): Defines a function to handle 404 errors.
6. View function decorators
Besides @app.route, Flask also supports other decorators for implementing more complex functionality.
Example:
@app.before_request: A function that runs before each request is handled.@app.after_request: A function that runs after each request is handled.@app.teardown_request: A function that runs after the request ends, used for cleanup work.
Example decorator usage:
Example
@
app.
before_request
def
before_request
(
)
:
(
'Before request'
)
@
app.
after_request
def
after_request
(
response
)
:
(
'After request'
)
return
response
@
app.
teardown_request
def
teardown_request
(
exception
)
:
(
'Teardown request'
)
7. Status codes returned by view functions
A view function can return not only content but also specify an HTTP status code.
Example
@
app.
route
(
'/status'
)
def
status
(
)
:
return
'Everything is OK'
,
200
A return status code of 200 indicates the request was successful.
Returns a response object with a status code.
Example
from
flask
import
Response
@
app.
route
(
'/error'
)
def
error
(
)
:
return
Response
(
'An error occurred'
,
status
=
500
)
A return status code of 500 indicates an internal server error.