title: Flask context digging description: Deeply understand the underlying working principles of Flask's four major context objects: current_app, g, request, and session.
Flask context digging: the underlying logic of current_app, g, request, and session
📂 Stage: Stage 5 - Advanced Advancement (Performance and Architecture) 🔗 Related chapters: 路由(Routing)艺术 · environment-setup
In Flask development, you will be frequently exposed tocurrent_app、g、requestandsessionthese four objects. They look like ordinary variables, but in fact they are the core mechanism that supports Flask applications to maintain data isolation under multi-user concurrency and flexibly access resources under application factory mode. This article will start from two context stack containers, break down their underlying working methods step by step, and attach code examples that you can get started with directly.
1. First clarify the relationship between "two major containers and four major components"
Flask maintains two sets of stack containers for each request, each layer carrying a specific context object. The overall structure is as follows:
- Application Context Stack: It lets you work without global
appvariables, you can also safely get the current application instance; at the same timegLike a sticky note, temporary data is passed throughout the request processing chain. - Request context stack: Responsible for storing the details of the next request and the user session. Once the request is completed, these two objects will be destroyed and will not pollute other requests.
With this layered view in place, let’s drill down one by one.
2. current_app: Solve the global access pain points under "Application Factory Mode"
In entry-level projects, we often write directlyapp = Flask(__name__)And then quote it everywhere. However, it is recommended to use application factory mode in production environment: pass acreate_app()The function dynamically creates the application. At this time, there is no ready-made function at the module level.appvariable.current_appIt is used in this scenario to safely obtain the "proxy" of the current Flask instance wherever the request is processed.
❌ Wrong Posture & ✅ Correct Posture
Summary: As long as it is in the view function,
before_request、after_requestUse it in the callback of Flask's automatic management context.current_app, it is safe and available.
3. g: "Exclusive temporary cache box" for each request
If you need to share data between multiple processing steps of a request (such as recording the currently logged in user, tracking ID), and don't want to pass these variables around,gIt is the most suitable container.
Core Features
- Request Isolation: Request A's
g.userWill not run to request B. - Auto Clear: When the request ends,
gAll data on it will be recycled immediately. - Not a global variable: It is only shared between functions of the same request** and will be invalid across requests.
Practical combat: perfect delivery from preprocessing to finishing
In this way, functions in the entire request process can passgGet the data you need without having to repeatedly query the database or pass parameters manually.
4. request: an object containing "all current HTTP request information"
requestProbably the most familiar context object, it packages all the information sent by the client. Remember: It can only be accessed in the view function or request hook, otherwise it will reportRuntimeError。
High frequency usage quick check
requestThe content is very rich, only the most common categories are listed above. You can continue exploring in the official documentationcookies、environand other advanced features.
5. session: "Cryptographically signed cookie storage"
Flask'ssessionQuite special: The data is stored in the browser's cookie, not in the server's memory. To prevent user tampering, Flask usesSECRET_KEYHMAC-sign the content. The browser can decode and see the content, but as long as the content is modified, the signature will become invalid and the request will be rejected.
Core Features
- Storage Location: Browser Cookie (non-server).
- Security mechanism: Base64 encoding + signature verification, unforgeable.
- Lifetime: It expires when the browser is closed by default, and can be extended through configuration.
- Capacity limit: Cookies usually do not exceed 4 KB, so do not stuff large pieces of data into them.
Practical operation: login, read, logout
6. Underlying core: "Thread/Coroutine Security Isolation" implemented by werkzeug.local
Many beginners will wonder: why multiple users access at the same timerequestBut they won't cover each other? The answer lies in the underlying Werkzeug library of Flask which providesLocalandLocalStackTwo tools that maintain separate storage space for each thread (or coroutine).
A simple understanding of how Local works
You can imagine that there is a large global dictionary, whose key is the unique identifier of the current thread (or coroutine), and the value is the thread's own small dictionary. When the code accessesrequestWhen, we are actually querying全局字典[当前线程ID]["request"]. Therefore, the data of different threads are naturally isolated.
Flask also uses a stack structure on top of this, which can elegantly support context nesting (such as temporarily pushing a new request in a test), which is why we often say "application context stack" and "request context stack".
When do I need to manually push the context?
Flask will automatically push the view function for you when it is running. However, in scenarios such as test scripts, offline tasks, and command line tools, the context will not automatically exist. In this case, it needs to be triggered manually:
Armed with this, you understand the complete picture of Flask context "automatic management" and "manual intervention".
7. Four context cheat sheets
🔗 Extended reading

