Flask View Function API
View functions can have special attributes attached to control routing behavior. These attributes usually do not need to be set manually, but are very useful in certain advanced scenarios.
View function attributes
| Property | Type | Default value | Description |
|---|---|---|---|
| __name__ | str | Function Name | Used as the endpoint name. In blueprints, the blueprint name prefix is automatically prepended. |
| methods | list | None | The HTTP methods accepted by the view function. If not specified in add_url_rule, this value is used. |
| required_methods | set | None | HTTP methods that must be added. Even if add_url_rule explicitly specifies methods, these methods will still be forcibly added. |
| provide_automatic_options | bool | None | Whether to automatically handle OPTIONS requests. Set to False to customize the OPTIONS response. |
Use Case
| Scenarios | Attribute Used | Description |
|---|---|---|
| Custom OPTIONS Response | provide_automatic_options=False | Prevent Flask from automatically generating OPTIONS; let the view function handle it itself. |
| Setting Methods in Decorators | methods | Decorators can pre-set the method list of the view function. |
| Force-add methods | required_methods | Ensure that specific methods are always registered |
Code Examples
Example
from flask import Flask, request
app = Flask(__name__)
# Example 1: Custom OPTIONS response
def custom_endpoint():
if request.method == "OPTIONS":
# Return a custom OPTIONS response
return "", 200, {"Allow": "GET, POST"}
return "Hello, EXAMPLE!"
# Disable automatic OPTIONS
custom_endpoint.provide_automatic_options = False
custom_endpoint.methods = ["GET", "POST", "OPTIONS"]
app.add_url_rule("/custom", view_func=custom_endpoint)
# Example 2: Define a decorator to automatically set methods
def api_view(func):
"""Custom decorator: automatically sets methods for view functions"""
func.methods = ["GET", "POST"]
return func
@api_view
def api_handler():
return {"status": "ok"}
app.add_url_rule("/api", view_func=api_handler)
# At this point, methods will automatically be read from the function attributes
app = Flask(__name__)
# Example 1: Custom OPTIONS response
def custom_endpoint():
if request.method == "OPTIONS":
# Return a custom OPTIONS response
return "", 200, {"Allow": "GET, POST"}
return "Hello, EXAMPLE!"
# Disable automatic OPTIONS
custom_endpoint.provide_automatic_options = False
custom_endpoint.methods = ["GET", "POST", "OPTIONS"]
app.add_url_rule("/custom", view_func=custom_endpoint)
# Example 2: Define a decorator to automatically set methods
def api_view(func):
"""Custom decorator: automatically sets methods for view functions"""
func.methods = ["GET", "POST"]
return func
@api_view
def api_handler():
return {"status": "ok"}
app.add_url_rule("/api", view_func=api_handler)
# At this point, methods will automatically be read from the function attributes