Flask view functions
View functions are the core part of a Flask application; they handle requests and generate responses.
View functions are closely tied to routing, using routes to 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.
- Define view function: View functions are the core functionality that processes requests and returns responses.
- Receive request data: Use
requestUse the object to obtain URL parameters, form data, query parameters, and so on. - Return a response: Can return strings, HTML, JSON, or custom response objects.
- Handle requests and responses: Use
requestobject andmake_responseUsed to handle requests and generate custom responses. - handle errors: Handle exceptions within view functions or use Flask's error handling mechanism.
- Decorators for view functions: Use
@app.before_request、@app.after_requestDecorators handle logic before and after requests. - Status codes returned by view functionsCan specify HTTP status codes to indicate the result of request processing.
1. Define view functions
A view function is an ordinary Python function that receives requests and returns responses. View functions are usually used together with routes, mapping URLs to view functions through decorators.
Example
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, World!'
@app.route('/'): Map the root URL/tohomethe view function.def home()View function, returns a string'Hello, World!'as the response.
2. Receive request data
View functions can receive different types of request data, including URL parameters, form data, query parameters, etc.
Get URL parameters:
Example
def greet(name):
return f'Hello, {name}!'
<name>is a URL parameter passed to the view function.greet。
Get form data:
Example
@app.route('/submit', methods=['POST'])
def submit():
username = request.form.get('username')
return f'Form submitted by {username}!'
request.form.get('username'): Retrieve the username field from the form data in a POST request.
Get query parameters:
Example
def search():
query = request.args.get('query')
return f'Search results for: {query}'
request.args.get('query'): Retrieve the query parameter query from a GET request.
3. Return response
View functions can return multiple types of responses, including strings, HTML, JSON, or custom response objects.
Return string:
Example
def message():
return 'This is a simple message.'
Return HTML templates:
Example
@app.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name)
render_template('hello.html', name=name)Render the HTML template hello.html, and pass the name variable to the template.
Return JSON data:
Example
@app.route('/api/data')
def api_data():
data = {'key': 'value'}
return jsonify(data)
jsonify(data)Convert a Python dictionary to a JSON response.
Return custom response objects:
Example
@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): Create a custom response object and set response headers.
4. Handle requests and responses
View functions can access the request object and generate responses based on request data. You can use the request object to get request information and make_response to create custom responses.
Using the request object:
Example
@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'): Retrieve the User-Agent information from the request headers.
Use make_response:
Example
@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'): Create a response object and set custom header information.
5. Handle errors
Exceptions can be handled inside view functions, or errors can be handled using Flask's error handling mechanism.
Handle errors in view functions:
Example
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 division-by-zero errors and return a custom error message and status code.
Global error handling:
Example
def not_found(error):
return 'Page not found', 404
@app.errorhandler(404): Define a function that handles 404 errors.
6. Decorators for view functions
In addition to @app.route, Flask also supports other decorators for implementing more complex functionality.
Example:
@app.before_requestFunctions that run before each request is processed.@app.after_requestFunctions that run after each request is processed.@app.teardown_requestFunctions that run after the request ends, used for cleanup.
Example decorator usage:
Example
def before_request():
print('Before request')
@app.after_request
def after_request(response):
print('After request')
return response
@app.teardown_request
def teardown_request(exception):
print('Teardown request')
7. Status codes returned by view functions
View functions can not only return content, but also specify HTTP status codes.
Example
def status():
return 'Everything is OK', 200
Returning status code 200 indicates a successful request.
Return a response object with a status code:
Example
@app.route('/error')
def error():
return Response('An error occurred', status=500)
Returning status code 500 indicates a server internal error.
other extensions