| 1 |
import warnings |
| 2 |
from datetime import timedelta as TimeDelta |
| 3 |
from typing import Optional |
| 4 |
|
| 5 |
from cachelib.file import FileSystemCache |
| 6 |
from flask import Flask |
| 7 |
|
| 8 |
from .._utils import total_seconds |
| 9 |
from ..base import ServerSideSession, ServerSideSessionInterface |
| 10 |
from ..defaults import Defaults |
| 11 |
|
| 12 |
|
| 13 |
class CacheLibSession(ServerSideSession): |
| 14 |
pass |
| 15 |
|
| 16 |
|
| 17 |
class CacheLibSessionInterface(ServerSideSessionInterface): |
| 18 |
"""Uses any :class:`cachelib` backend as a session storage. |
| 19 |
|
| 20 |
:param client: A :class:`cachelib` backend instance. |
| 21 |
:param key_prefix: A prefix that is added to storage keys. |
| 22 |
:param use_signer: Whether to sign the session id cookie or not. |
| 23 |
:param permanent: Whether to use permanent session or not. |
| 24 |
:param sid_length: The length of the generated session id in bytes. |
| 25 |
:param serialization_format: The serialization format to use for the session data. |
| 26 |
""" |
| 27 |
|
| 28 |
session_class = CacheLibSession |
| 29 |
ttl = True |
| 30 |
|
| 31 |
def __init__( |
| 32 |
self, |
| 33 |
app: Flask = None, |
| 34 |
client: Optional[FileSystemCache] = Defaults.SESSION_CACHELIB, |
| 35 |
key_prefix: str = Defaults.SESSION_KEY_PREFIX, |
| 36 |
use_signer: bool = Defaults.SESSION_USE_SIGNER, |
| 37 |
permanent: bool = Defaults.SESSION_PERMANENT, |
| 38 |
sid_length: int = Defaults.SESSION_ID_LENGTH, |
| 39 |
serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT, |
| 40 |
): |
| 41 |
|
| 42 |
if client is None: |
| 43 |
warnings.warn( |
| 44 |
"No valid cachelib instance provided, attempting to create a new instance on localhost with default settings.", |
| 45 |
RuntimeWarning, |
| 46 |
stacklevel=1, |
| 47 |
) |
| 48 |
client = FileSystemCache("flask_session", threshold=500) |
| 49 |
|
| 50 |
self.cache = client |
| 51 |
|
| 52 |
super().__init__( |
| 53 |
None, key_prefix, use_signer, permanent, sid_length, serialization_format |
| 54 |
) |
| 55 |
|
| 56 |
def _retrieve_session_data(self, store_id: str) -> Optional[dict]: |
| 57 |
# Get the saved session (item) from the database |
| 58 |
return self.cache.get(store_id) |
| 59 |
|
| 60 |
def _delete_session(self, store_id: str) -> None: |
| 61 |
self.cache.delete(store_id) |
| 62 |
|
| 63 |
def _upsert_session( |
| 64 |
self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str |
| 65 |
) -> None: |
| 66 |
storage_time_to_live = total_seconds(session_lifetime) |
| 67 |
|
| 68 |
# Serialize the session data (or just cast into dictionary in this case) |
| 69 |
session_data = dict(session) |
| 70 |
|
| 71 |
# Update existing or create new session in the database |
| 72 |
self.cache.set( |
| 73 |
key=store_id, |
| 74 |
value=session_data, |
| 75 |
timeout=storage_time_to_live, |
| 76 |
) |