πŸ” 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 πŸš€