Flask 实用函数与类 API
Flask 提供了一系列全局可用函数,用于生成 URL、终止请求、构建响应等常见操作。
全部通过 from flask import ... 导入。
全局代理对象
| 对象 | 类型 | 说明 |
|---|---|---|
| current_app | 代理 → Flask | 指向当前活跃的 Flask 应用实例。在应用上下文中可用 |
URL 和重定向
| 函数 | 签名 | 说明 |
|---|---|---|
| url_for | (endpoint, *, _anchor, _method, _scheme, _external, **values) | 根据视图函数名生成 URL。_external=True 生成绝对 URL |
| redirect | (location, code=303, Response=None) | 创建重定向响应。code 默认 303(See Other) |
请求终止和响应构建
| 函数 | 签名 | 说明 |
|---|---|---|
| abort | (code, *args, **kwargs) | 立即终止请求并返回 HTTP 错误。code 为状态码,description 为描述 |
| make_response | (*args) | 将视图返回值转换为 Response 对象。传多个参数时按元组处理 |
| after_this_request | (func) | 注册一个仅在当前请求后执行一次的函数。用于动态添加 after_request |
上下文检查
| 函数 | 说明 |
|---|---|
| has_request_context() | 返回 True 如果当前有活跃的请求上下文 |
| has_app_context() | 返回 True 如果当前有活跃的应用上下文 |
| copy_current_request_context(func) | 装饰器。复制当前请求上下文,使被装饰的函数在上下文外运行时仍能访问 request、g 等 |
文件发送
| 函数 | 签名 | 说明 |
|---|---|---|
| send_file | (path_or_file, mimetype, as_attachment, download_name, conditional, etag, last_modified, max_age) | 发送文件内容。as_attachment=True 触发下载。支持条件请求和 ETag |
| send_from_directory | (directory, path, **kwargs) | 从指定目录安全发送文件。使用 safe_join 防路径遍历攻击 |
代码示例
实例
from flask import (Flask, current_app, url_for, redirect,
abort, make_response, after_this_request,
has_request_context, send_file, send_from_directory)
app = Flask(__name__)
@app.route("/")
def index():
# url_for 生成 URL
login_url = url_for("login")
# 生成绝对 URL(含域名)
full_url = url_for("profile", username="runoob", _external=True)
return f'<a href="{login_url}">Login</a>'
@app.route("/redirect-me")
def redirect_me():
# 重定向到首页
return redirect(url_for("index"))
@app.route("/profile/<username>")
def profile(username):
return f"Profile: {username}"
@app.route("/admin")
def admin():
# 未授权访问,返回 403
abort(403, description="Access denied")
@app.route("/download")
def download():
# 发送文件(触发浏览器下载)
return send_from_directory("uploads", "report.pdf",
as_attachment=True,
download_name="runoob_report.pdf")
@app.route("/custom-response")
def custom_response():
# 手动构建响应对象
resp = make_response("<h1>Custom</h1>")
resp.headers["X-Powered-By"] = "RUNOOB"
@after_this_request
def log_response(response):
app.logger.info(f"Request to {request.path} done, status={response.status_code}")
return response
return resp
abort, make_response, after_this_request,
has_request_context, send_file, send_from_directory)
app = Flask(__name__)
@app.route("/")
def index():
# url_for 生成 URL
login_url = url_for("login")
# 生成绝对 URL(含域名)
full_url = url_for("profile", username="runoob", _external=True)
return f'<a href="{login_url}">Login</a>'
@app.route("/redirect-me")
def redirect_me():
# 重定向到首页
return redirect(url_for("index"))
@app.route("/profile/<username>")
def profile(username):
return f"Profile: {username}"
@app.route("/admin")
def admin():
# 未授权访问,返回 403
abort(403, description="Access denied")
@app.route("/download")
def download():
# 发送文件(触发浏览器下载)
return send_from_directory("uploads", "report.pdf",
as_attachment=True,
download_name="runoob_report.pdf")
@app.route("/custom-response")
def custom_response():
# 手动构建响应对象
resp = make_response("<h1>Custom</h1>")
resp.headers["X-Powered-By"] = "RUNOOB"
@after_this_request
def log_response(response):
app.logger.info(f"Request to {request.path} done, status={response.status_code}")
return response
return resp
