Flask 视图函数 API
视图函数可以附加特殊属性来控制路由行为。这些属性通常不需要手动设置,但在某些高级场景下非常有用。
视图函数属性
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| __name__ | str | 函数名 | 用作 endpoint 名。在蓝图中会自动加蓝图名前缀 |
| methods | list | None | 视图函数接受的 HTTP 方法。若未在 add_url_rule 中指定,则使用此值 |
| required_methods | set | None | 必须添加的 HTTP 方法。即使 add_url_rule 显式指定了 methods,这些方法也会被强制添加 |
| provide_automatic_options | bool | None | 是否自动处理 OPTIONS 请求。设为 False 可自定义 OPTIONS 响应 |
使用场景
| 场景 | 使用的属性 | 说明 |
|---|---|---|
| 自定义 OPTIONS 响应 | provide_automatic_options=False | 阻止 Flask 自动生成 OPTIONS,由视图函数自行处理 |
| 在装饰器中设置方法 | methods | 装饰器可预先设置视图函数的方法列表 |
| 强制添加方法 | required_methods | 确保特定方法总是被注册 |
代码示例
实例
from flask import Flask, request
app = Flask(__name__)
# 示例1:自定义 OPTIONS 响应
def custom_endpoint():
if request.method == "OPTIONS":
# 返回自定义的 OPTIONS 响应
return "", 200, {"Allow": "GET, POST"}
return "Hello, RUNOOB!"
# 关闭自动 OPTIONS
custom_endpoint.provide_automatic_options = False
custom_endpoint.methods = ["GET", "POST", "OPTIONS"]
app.add_url_rule("/custom", view_func=custom_endpoint)
# 示例2:定义装饰器自动设置方法
def api_view(func):
"""自定义装饰器:自动为视图函数设置方法"""
func.methods = ["GET", "POST"]
return func
@api_view
def api_handler():
return {"status": "ok"}
app.add_url_rule("/api", view_func=api_handler)
# 此时 methods 会自动从函数属性中读取
app = Flask(__name__)
# 示例1:自定义 OPTIONS 响应
def custom_endpoint():
if request.method == "OPTIONS":
# 返回自定义的 OPTIONS 响应
return "", 200, {"Allow": "GET, POST"}
return "Hello, RUNOOB!"
# 关闭自动 OPTIONS
custom_endpoint.provide_automatic_options = False
custom_endpoint.methods = ["GET", "POST", "OPTIONS"]
app.add_url_rule("/custom", view_func=custom_endpoint)
# 示例2:定义装饰器自动设置方法
def api_view(func):
"""自定义装饰器:自动为视图函数设置方法"""
func.methods = ["GET", "POST"]
return func
@api_view
def api_handler():
return {"status": "ok"}
app.add_url_rule("/api", view_func=api_handler)
# 此时 methods 会自动从函数属性中读取
