会话框架
存储与单个访客关联的数据
会话框架 是 CoddyKit 上的免费 Django Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Sessions Exist
HTTP forgets you between requests. The session framework lets Django remember each visitor across page loads, so a login or a cart can survive. 🍪
What a Session Stores
A session is a small bag of data tied to one visitor. Django keeps it on the server and gives the browser only a key to find it again.
The Session Cookie
Django sets a cookie named sessionid in the browser. That cookie holds just the session key, never your private data, which stays safe on the server.
It Is Already On
The SessionMiddleware ships enabled in every new project, so sessions work out of the box without any extra setup from you.
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
]The Sessions App
The django.contrib.sessions app lives in INSTALLED_APPS and creates a table to hold session data after you run migrate.
Where Data Lives
By default Django stores sessions in the database. Each row holds the key, the encoded data, and an expiry date for that visitor.
Choosing a Backend
You pick storage with SESSION_ENGINE. Cache or cached_db backends keep sessions in memory for far faster reads on busy sites.
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'Accessing the Session
In any view, the session hangs off the request as request.session. It behaves like a normal Python dictionary you can read and write.
def home(request):
request.session['theme'] = 'dark'
return render(request, 'home.html')Sessions Expire
Sessions do not last forever. SESSION_COOKIE_AGE sets the lifetime in seconds, defaulting to two weeks before a visitor is forgotten.
SESSION_COOKIE_AGE = 1209600 # two weeksClearing Old Sessions
Expired rows linger in the database. Run clearsessions on a schedule to delete stale data and keep the table tidy.
python manage.py clearsessionsAnonymous and Logged In
Sessions track both anonymous and logged-in visitors. That is how a guest can fill a cart before they ever create an account.
Quick Check
Let us check where session data actually lives.
Recap
You met the session framework: it remembers visitors across requests, stores data server-side, and works automatically through SessionMiddleware. Next you will read and write it. ✅
常见问题解答
「会话框架」课时是免费的吗?
是的 — 「会话框架」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。
「会话框架」这节课中我会学到什么?
存储与单个访客关联的数据 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Django Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「会话框架」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Django Academy 课中编写并运行代码吗?
能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。