上下文局部变量与线程安全
了解代理如何在不同请求间保持正确
上下文局部变量与线程安全 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Magic Question
How does one global request object stay correct when many visitors hit your app at once? The answer is context locals.
They Look Global
Objects like request and g look like plain globals you import once. But they are special proxies, not ordinary shared variables.
from flask import requestProxies Point Per Context
A proxy forwards every access to the real object for the current context. Each request sees its own data through the same import.
Context Locals
Flask calls these context locals. They behave like thread locals but key off the active context, so concurrent requests never collide.
Thread Safety
Two threads handling two requests each get their own bound context. So request in one thread never shows another thread's data.
Beyond Threads
Modern Flask uses contextvars, so isolation holds even for greenlets and async tasks, not just operating system threads.
One Import, Many Values
This is why a single import at the top of your file is safe. The proxy resolves to a different real object for every request.
Watch the Background
Spawn a raw thread from a view and it has no context. Accessing request there fails unless you push a context yourself.
Pass Values, Not Proxies
Hand a background worker the actual value it needs, like a user id, instead of the request proxy, which will be gone by then.
uid = request.args.get("id")
start_job(uid)Get the Real Object
Need the underlying object behind a proxy? Use _get_current_object, but reach for it rarely and only when you truly must.
real = request._get_current_object()Why It Feels Easy
Context locals are why Flask feels simple: you import request once and trust it, while the framework quietly keeps every request isolated.
Quick Check
Let us confirm how proxies stay safe.
Recap
Flask's globals are really context-local proxies. They resolve per request, keeping threads and async tasks isolated, so one import stays safe everywhere. 🎉
常见问题解答
「上下文局部变量与线程安全」课时是免费的吗?
是的 — 「上下文局部变量与线程安全」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。
「上下文局部变量与线程安全」这节课中我会学到什么?
了解代理如何在不同请求间保持正确 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flask Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「上下文局部变量与线程安全」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flask Academy 课中编写并运行代码吗?
能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 应用上下文与请求上下文
- current_app 与 g 对象
- 上下文局部变量与线程安全
- 在脚本和 Shell 中推入上下文