π 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.
For important sessions or sessions that require immediate saving, you can use the method
saveon request session to explicitly save the request session.
π οΈ 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 π