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 🚀