Skip to content

上下文

推送完上下文之后就可以调用了current_app.name

shell
from flask import Flask,current_app
app = Flask(__name__)
app_ctx = app.app_context()
app_ctx.push()
# print(app.url_map)
print("app name",current_app.name)
# app_ctx.pop()

查看代码:https://gitee.com/PatrickW/flask-web/blob/master/src/3context.py

在Flask中有两种上下文:应用上下文和请求上下文

应用上下文

current_app: 当前激活的应用程序实例

g: 处理请求时用作临时存储的对象。每次请求都会重设这个变量

请求上下文

request: 请求对象,封装了客户端发出的HTTP请求中的内容

session: 用户会话,用于存储请求之间需要记住的值的词典

request

请求钩子 before_request: 在请求处理之前调用 before_first_request: 在第一个请求之前调用 after_request: 在请求处理之后调用,比如关闭数据库连接 teardown_request: 在请求之后调用,无论请求是否成功

python
# 清理工作
@app.teardown_appcontext
def teardown_db(exception):
    print("teardown_db")
    db = g.pop('db', None)
    
    if db is not None:
        db.close()

# 在请求之前设置数据
@app.before_request
def before_request():
    g.request_start_time = time.time()

@app.route('/')
def index():
    g.name = 'diyai1314'
    response = make_response('<h1>Hello {} {}!</h1>'.format( g.name,g.request_start_time))
    response.set_cookie('who', g.name) # 设置cookie
    response.headers['X-Foo'] = 'my header'
    response.status_code = 200
    response.content_type = 'text/html'

    # response.delete_cookie('who') # 删除cookie
    return response

response

python
@app.route('/')
def index():
    response = make_response('<h1>Hello Flask!</h1>')
    response.set_cookie('who', 'diyai1314') # 设置cookie
    response.headers['X-Foo'] = 'my header'
    response.status_code = 200
    response.content_type = 'text/html'
    response.delete_cookie('who') # 删除cookie
    return response

redirect

python
@app.route('/redirect')
def redirect_route():
    return redirect("https://diyai.cn")

abort

python
@app.route('/abort')
def abort_route():
    abort(502)