Tables

We store the session tokens in SessionsBase table, and the user credentials in BaseUser table.


Migrations

We recommend creating these tables using migrations.

You can add piccolo_api.session_auth.piccolo_app to the apps arguments of the AppRegistry in piccolo_conf.py.

APP_REGISTRY = AppRegistry(
    apps=[
        ...
        "piccolo_api.session_auth.piccolo_app",
        "piccolo.apps.user.piccolo_app",
        ...
    ]
)

To learn more about Piccolo apps, see the Piccolo docs.

To run the migrations and create the tables, run:

piccolo migrations forwards user
piccolo migrations forwards session_auth

Creating them manually

If you prefer not to use migrations, and want to create them manually, you can do this instead:

from piccolo_api.session_auth.tables import SessionsBase
from piccolo.apps.user.tables import BaseUser
from piccolo.tables import create_tables

create_tables(BaseUser, SessionsBase, if_not_exists=True)

Source

SessionsBase

class piccolo_api.session_auth.tables.SessionsBase(_data: Dict[Column, Any] | None = None, _ignore_missing: bool = False, _exists_in_db: bool = False, **kwargs)[source]

Use this table, or inherit from it, to create a session store.

async classmethod create_session(user_id: int, expiry_date: datetime | None = None, max_expiry_date: datetime | None = None) SessionsBase[source]

Creates a session in the database.

classmethod create_session_sync(user_id: int, expiry_date: datetime | None = None) SessionsBase[source]

A sync equivalent of create_session().

async classmethod get_user_id(token: str, increase_expiry: timedelta | None = None) int | None[source]

Returns the user_id if the given token is valid, otherwise None.

Parameters:

increase_expiry – If set, the expiry_date will be increased by the given amount if it’s close to expiring. If it has already expired, nothing happens. The max_expiry_date remains the same, so there’s a hard limit on how long a session can be used for.

classmethod get_user_id_sync(token: str) int | None[source]

A sync wrapper around get_user_id().

async classmethod remove_session(token: str)[source]

Deletes a matching session from the database.

classmethod remove_session_sync(token: str)[source]

A sync wrapper around remove_session().

expiry_date: Timestamp

Stores the expiry date for this session.

id: Serial

An alias to an autoincrementing integer column in Postgres.

max_expiry_date: Timestamp

We set a hard limit on the expiry date - it can keep on getting extended up until this value, after which it’s best to invalidate it, and either require login again, or just create a new session token.

token: Varchar

Stores the session token.

user_id: Integer

Stores the user ID.