๐ Sessions in Duckยถ
Duck provides robust session management using SessionMiddleware.
This middleware is responsible for loading, saving, and managing sessions in a flexible way.
Session Storage Optionsยถ
Duck supports multiple session storage backends:
In-memory cache:
duck.utils.caching.InMemoryCacheโ fast but temporary.Key-as-folder cache:
duck.utils.caching.KeyAsFolderCacheโ stores sessions in filesystem folders.Dynamic file cache:
duck.utils.caching.DynamicFileCacheโ flexible file-based storage.
You can also implement a custom cache class, but it must provide:
set,get,delete,clear, andsavemethods.
Accessing Sessionsยถ
Access the request session via
request.SESSIONorrequest.session.Sessions are lazily saved, meaning they are written only if there are changes.
To change session storage, set
SESSION_STORAGEinsettings.py.
Example:ยถ
# views.py
from duck.http.response import HttpResponse
def some_view(request):
request.SESSION["some_key"] = some_value # Or use request.session
return HttpResponse("Hello world")
Notes:
Request sessions are lazily saved if changes are detected.
Warning
It is generally not recommended to explicitly save a session. Doing so can prevent the SessionMiddleware from accurately detecting whether the session data has changed, which is how it determines whether updated session cookies need to be sent to the client.
Instead, allow the middleware to manage session persistence automatically. If you explicitly save the session, you may need to manually mark the session as modified by setting request.SESSION.modified = True. This ensures that request.SESSION.needs_update() returns True, allowing the middleware to issue any required cookie updates.
Session Settingsยถ
Most defaults are safe, but you can customize as needed:
Session Engineยถ
The engine handling session operations.
Avoid overriding unless necessary.
For Django integration (
USE_DJANGO=True), you must implement a custom Django session backend.
Session Directoryยถ
Directory where session files are stored (if using file-based storage).
Database-backed sessions: set to
None.Directory will be auto-created if it doesnโt exist.
Session Durationยถ
Lifetime of the session in seconds.
Default: 7 days (
604800seconds)
Session Expire at Browser Closeยถ
Whether the session expires when the browser is closed.
Default:
False
Notes & Tipsยถ
Duck sessions are lightweight and flexible for both short and long-lasting sessions.
Always pick a session backend that fits your performance and persistence needs.
Combine with Duckโs middleware and async features for secure, scalable web apps.
โจ With Duck sessions, you can manage user data efficiently while keeping control over cookies, storage, and lifetime ๐