Skip to main content

Database-backed sessions for managing user state across requests.

Project description

plain.sessions

Database-backed sessions for managing user state across requests.

Overview

The plain.sessions package provides database-backed session management for Plain applications. Sessions allow you to store and retrieve arbitrary data on a per-visitor basis, using a session key stored in a cookie.

Sessions are implemented as a dictionary-like object that automatically handles persistence to the database.

Basic usage

In views that inherit from SessionViewMixin, you can use self.session like a standard Python dictionary:

from plain.sessions.views import SessionViewMixin
from plain.views import View

class MyView(SessionViewMixin, View):
    def get(self):
        # Store values in the session
        self.session['username'] = 'jane'
        self.session['cart_items'] = [1, 2, 3]

        # Retrieve values from the session
        username = self.session.get('username')
        cart_items = self.session.get('cart_items', [])

        # Check if a key exists
        if 'username' in self.session:
            # User has a session
            pass

        # Delete values from the session
        del self.session['cart_items']

Outside of views, you can use get_request_session():

from plain.sessions import get_request_session

session = get_request_session(request)
session['key'] = 'value'

The session data is automatically saved when you set or delete values. Sessions are stored in the database using the Session model.

Session configuration

Sessions can be configured through various settings:

# Cookie name (default: "sessionid")
SESSION_COOKIE_NAME = "sessionid"

# Age of cookie in seconds (default: 2 weeks)
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2

# Domain for session cookie (None for standard domain cookie)
SESSION_COOKIE_DOMAIN = None

# Whether the session cookie should be secure (https:// only)
SESSION_COOKIE_SECURE = True

# The path of the session cookie
SESSION_COOKIE_PATH = "/"

# Whether to use the HttpOnly flag
SESSION_COOKIE_HTTPONLY = True

# Whether to set the flag restricting cookie leaks on cross-site requests
# Can be 'Lax', 'Strict', 'None', or False
SESSION_COOKIE_SAMESITE = "Lax"

# Whether to save the session data on every request
# False (default) = save only when modified, True = save on every access
SESSION_SAVE_EVERY_REQUEST = False

# Whether a user's session cookie expires when the browser is closed
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

Session expiration

Sessions expire SESSION_COOKIE_AGE seconds after they are last saved (not last accessed).

By default (SESSION_SAVE_EVERY_REQUEST = False), sessions are only saved when modified. For authenticated users, this means the expiration timer resets on login/logout but not when just browsing pages. Users will be logged out after SESSION_COOKIE_AGE even if actively using the site.

To extend sessions on every page access, set SESSION_SAVE_EVERY_REQUEST = True. This creates a sliding window where users stay logged in as long as they visit within SESSION_COOKIE_AGE, but increases database writes

Session management

The SessionStore class provides additional methods for managing sessions:

Flushing sessions

To completely remove the current session data and regenerate the session key:

# In a view with SessionViewMixin
self.session.flush()

# Outside a view
from plain.sessions import get_request_session
session = get_request_session(request)
session.flush()

Cycling session keys

To create a new session key while retaining the current session data (useful for security purposes):

# In a view with SessionViewMixin
self.session.cycle_key()

# Outside a view
from plain.sessions import get_request_session
session = get_request_session(request)
session.cycle_key()

Checking if session is empty

# In a view with SessionViewMixin
if self.session.is_empty():
    # No session data exists
    pass

# Outside a view
from plain.sessions import get_request_session
session = get_request_session(request)
if session.is_empty():
    # No session data exists
    pass

Admin interface

The package includes an admin interface for viewing and managing sessions. Sessions can be viewed in the admin panel under the "Sessions" section, where you can:

  • Search sessions by session key
  • View session creation and expiration times
  • Delete expired or unwanted sessions

The SessionAdmin viewset provides the interface for managing sessions in the admin panel.

Installation

Install the plain.sessions package from PyPI:

uv add plain.sessions

Add plain.sessions to your INSTALLED_PACKAGES and include the SessionMiddleware in your middleware:

INSTALLED_PACKAGES = [
    # ...
    "plain.sessions",
]

MIDDLEWARE = [
    # ...
    "plain.sessions.middleware.SessionMiddleware",
    # ...
]

Run migrations to create the session table:

plain migrate plain.sessions

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

plain_sessions-0.40.0.tar.gz (15.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

plain_sessions-0.40.0-py3-none-any.whl (21.3 kB view details)

Uploaded Python 3

File details

Details for the file plain_sessions-0.40.0.tar.gz.

File metadata

  • Download URL: plain_sessions-0.40.0.tar.gz
  • Upload date:
  • Size: 15.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for plain_sessions-0.40.0.tar.gz
Algorithm Hash digest
SHA256 54fc223d99d2473a3b0de86e4368a5071f07b4eb233a97fb39e9118290071657
MD5 82c6168b977815f9b4371aca6dd63a87
BLAKE2b-256 158d5ee3e17d87c9f251550a4745b34fcbbd1d9ff22f6e48f8e309f1b0773f08

See more details on using hashes here.

File details

Details for the file plain_sessions-0.40.0-py3-none-any.whl.

File metadata

  • Download URL: plain_sessions-0.40.0-py3-none-any.whl
  • Upload date:
  • Size: 21.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for plain_sessions-0.40.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d03fccf465dedaaec67fad6aa5ed340ad8a0f35285d6a834ca1241d875c6604a
MD5 0eb15f2aaa415a2609e28ea0a62582ea
BLAKE2b-256 4126b98655cefb08316d3e41b6fb16a8b9a7ae7883015aca828f378bfc6b3c44

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page