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.

  1. Define view function: View functions are the core functionality that processes requests and returns responses.
  2. Receive request data: UserequestUse the object to obtain URL parameters, form data, query parameters, and so on.
  3. Return a response: Can return strings, HTML, JSON, or custom response objects.
  4. Handle requests and responses: Userequestobject andmake_responseUsed to handle requests and generate custom responses.
  5. handle errors: Handle exceptions within view functions or use Flask's error handling mechanism.
  6. Decorators for view functions: Use@app.before_request、@app.after_requestDecorators handle logic before and after requests.
  7. 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

from flask import Flask

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

@app.route('/greet/<name>')
def greet(name):
    return f'Hello, {name}!'
  • <name>is a URL parameter passed to the view function.greet。

Get 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'): Retrieve the username field from the form data in a POST request.

Get query parameters:

Example

@app.route('/search')
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

@app.route('/message')
def message():
    return 'This is a simple message.'

Return HTML templates:

Example

from flask import render_template

@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

from flask import jsonify

@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

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): 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

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'): Retrieve the User-Agent information from the request headers.

Use 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'): 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

@app.route('/divide/<int:x>/<int:y>')
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

@app.errorhandler(404)
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

@app.before_request
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

@app.route('/status')
def status():
    return 'Everything is OK', 200

Returning status code 200 indicates a successful request.

Return a response object with a status code:

Example

from flask import Response

@app.route('/error')
def error():
    return Response('An error occurred', status=500)

Returning status code 500 indicates a server internal error.

other extensions