๐Ÿ” Sessions in Duckยถ

Session Management
Duck Framework


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, and save methods.


Accessing Sessionsยถ

  • Access the request session via request.SESSION or request.session.

  • Sessions are lazily saved, meaning they are written only if there are changes.

  • To change session storage, set SESSION_STORAGE in settings.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 save on 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 (604800 seconds)

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 ๐Ÿš€