context in flask 2023-04-18
2024-04-09 16:15:28  阅读数 7602

flask

what is a flask application

a flask application is a normal, just a normal python object of class Flask. An instance of this class will be our WSGI application.

here is the simplest way to create a Flask instance

from flask import Flask

app = Flask(__name__)

it's the object app that takes the responsibility to handle requests

需要注意的是,在项目中,app是一个顶层对象

request context

  • When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server.

  • Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request. Flask uses the term context local for this.

  • Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.

If you try to access request, or anything that uses it, outside a request context, you’ll get this error message:
RuntimeError: Working outside of request context.

refer to https://flask.palletsprojects.com/en/2.2.x/reqcontext/

application context

Flask automatically pushes an application context when handling a request.

View functions, error handlers, and other functions that run during a request will have access to current_app, which is a proxy, pointing to the bound app.

Flask will also automatically push an app context when running CLI commands registered with Flask.cli using @app.cli.command().

Working outside of application context

If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:
RuntimeError: Working outside of application context.

如果在配置应用的时候(如初始化扩展)看到这样的错误信息,可以手动推入一个上下文以访问 app。在 with 语句中使用 app_context() 上下文管理器对象,所有在块内的运行的代码将可以访问 current_app

def create_app():
    app = Flask(__name__)

    with app.app_context():
        init_db()

    return app

refer to https://flask.palletsprojects.com/en/2.2.x/appcontext/#the-application-context

context in flask 就像 gin.context
区别在于,flask框架的extension都依赖context,换句话说,flask extension都建立在context之上;而gin框架只有http handler依赖gin.context,把需要的值从 context 拿出来之后交到业务逻辑层,就与 context 无关了

Lifetime of the Context

The application context is created and destroyed as necessary.

  • When a Flask application begins handling a request, it pushes an application context and a request context.
  • When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request.