| 1 |
import warnings |
| 2 |
from datetime import datetime |
| 3 |
from datetime import timedelta as TimeDelta |
| 4 |
from typing import Any, Optional |
| 5 |
|
| 6 |
from flask import Flask |
| 7 |
from flask_sqlalchemy import SQLAlchemy |
| 8 |
from itsdangerous import want_bytes |
| 9 |
from sqlalchemy import Column, DateTime, Integer, LargeBinary, Sequence, String |
| 10 |
|
| 11 |
from .._utils import retry_query |
| 12 |
from ..base import ServerSideSession, ServerSideSessionInterface |
| 13 |
from ..defaults import Defaults |
| 14 |
|
| 15 |
|
| 16 |
class SqlAlchemySession(ServerSideSession): |
| 17 |
pass |
| 18 |
|
| 19 |
|
| 20 |
def create_session_model(db, table_name, schema=None, bind_key=None, sequence=None): |
| 21 |
class Session(db.Model): |
| 22 |
__tablename__ = table_name |
| 23 |
__table_args__ = {"schema": schema} if schema else {} |
| 24 |
__bind_key__ = bind_key |
| 25 |
|
| 26 |
id = ( |
| 27 |
Column(Integer, Sequence(sequence), primary_key=True) |
| 28 |
if sequence |
| 29 |
else Column(Integer, primary_key=True) |
| 30 |
) |
| 31 |
session_id = Column(String(255), unique=True) |
| 32 |
data = Column(LargeBinary) |
| 33 |
expiry = Column(DateTime) |
| 34 |
|
| 35 |
def __init__(self, session_id: str, data: Any, expiry: datetime): |
| 36 |
self.session_id = session_id |
| 37 |
self.data = data |
| 38 |
self.expiry = expiry |
| 39 |
|
| 40 |
def __repr__(self): |
| 41 |
return f"<Session data {self.data}>" |
| 42 |
|
| 43 |
return Session |
| 44 |
|
| 45 |
|
| 46 |
class SqlAlchemySessionInterface(ServerSideSessionInterface): |
| 47 |
"""Uses the Flask-SQLAlchemy from a flask app as session storage. |
| 48 |
|
| 49 |
:param app: A Flask app instance. |
| 50 |
:param client: A Flask-SQLAlchemy instance. |
| 51 |
:param key_prefix: A prefix that is added to all storage keys. |
| 52 |
:param use_signer: Whether to sign the session id cookie or not. |
| 53 |
:param permanent: Whether to use permanent session or not. |
| 54 |
:param sid_length: The length of the generated session id in bytes. |
| 55 |
:param serialization_format: The serialization format to use for the session data. |
| 56 |
:param table: The table name you want to use. |
| 57 |
:param sequence: The sequence to use for the primary key if needed. |
| 58 |
:param schema: The db schema to use. |
| 59 |
:param bind_key: The db bind key to use. |
| 60 |
:param cleanup_n_requests: Delete expired sessions on average every N requests. |
| 61 |
|
| 62 |
.. versionadded:: 0.7 |
| 63 |
db changed to client to be standard on all session interfaces. |
| 64 |
The `cleanup_n_request` parameter was added. |
| 65 |
|
| 66 |
.. versionadded:: 0.6 |
| 67 |
The `sid_length`, `sequence`, `schema` and `bind_key` parameters were added. |
| 68 |
|
| 69 |
.. versionadded:: 0.2 |
| 70 |
The `use_signer` parameter was added. |
| 71 |
""" |
| 72 |
|
| 73 |
session_class = SqlAlchemySession |
| 74 |
ttl = False |
| 75 |
|
| 76 |
def __init__( |
| 77 |
self, |
| 78 |
app: Optional[Flask], |
| 79 |
client: Optional[SQLAlchemy] = Defaults.SESSION_SQLALCHEMY, |
| 80 |
key_prefix: str = Defaults.SESSION_KEY_PREFIX, |
| 81 |
use_signer: bool = Defaults.SESSION_USE_SIGNER, |
| 82 |
permanent: bool = Defaults.SESSION_PERMANENT, |
| 83 |
sid_length: int = Defaults.SESSION_ID_LENGTH, |
| 84 |
serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT, |
| 85 |
table: str = Defaults.SESSION_SQLALCHEMY_TABLE, |
| 86 |
sequence: Optional[str] = Defaults.SESSION_SQLALCHEMY_SEQUENCE, |
| 87 |
schema: Optional[str] = Defaults.SESSION_SQLALCHEMY_SCHEMA, |
| 88 |
bind_key: Optional[str] = Defaults.SESSION_SQLALCHEMY_BIND_KEY, |
| 89 |
cleanup_n_requests: Optional[int] = Defaults.SESSION_CLEANUP_N_REQUESTS, |
| 90 |
): |
| 91 |
self.app = app |
| 92 |
|
| 93 |
if client is None or not isinstance(client, SQLAlchemy): |
| 94 |
warnings.warn( |
| 95 |
"No valid SQLAlchemy instance provided, attempting to create a new instance on localhost with default settings.", |
| 96 |
RuntimeWarning, |
| 97 |
stacklevel=1, |
| 98 |
) |
| 99 |
client = SQLAlchemy(app) |
| 100 |
self.client = client |
| 101 |
|
| 102 |
# Create the session model |
| 103 |
self.sql_session_model = create_session_model( |
| 104 |
client, table, schema, bind_key, sequence |
| 105 |
) |
| 106 |
# Create the table if it does not exist |
| 107 |
with app.app_context(): |
| 108 |
if bind_key: |
| 109 |
engine = self.client.get_engine(app, bind=bind_key) |
| 110 |
else: |
| 111 |
engine = self.client.engine |
| 112 |
self.sql_session_model.__table__.create(bind=engine, checkfirst=True) |
| 113 |
|
| 114 |
super().__init__( |
| 115 |
app, |
| 116 |
key_prefix, |
| 117 |
use_signer, |
| 118 |
permanent, |
| 119 |
sid_length, |
| 120 |
serialization_format, |
| 121 |
cleanup_n_requests, |
| 122 |
) |
| 123 |
|
| 124 |
@retry_query() |
| 125 |
def _delete_expired_sessions(self) -> None: |
| 126 |
try: |
| 127 |
self.client.session.query(self.sql_session_model).filter( |
| 128 |
self.sql_session_model.expiry <= datetime.utcnow() |
| 129 |
).delete(synchronize_session=False) |
| 130 |
self.client.session.commit() |
| 131 |
except Exception: |
| 132 |
self.client.session.rollback() |
| 133 |
raise |
| 134 |
|
| 135 |
@retry_query() |
| 136 |
def _retrieve_session_data(self, store_id: str) -> Optional[dict]: |
| 137 |
# Get the saved session (record) from the database |
| 138 |
record = self.sql_session_model.query.filter_by(session_id=store_id).first() |
| 139 |
|
| 140 |
# "Delete the session record if it is expired as SQL has no TTL ability |
| 141 |
if record and (record.expiry is None or record.expiry <= datetime.utcnow()): |
| 142 |
try: |
| 143 |
self.client.session.delete(record) |
| 144 |
self.client.session.commit() |
| 145 |
except Exception: |
| 146 |
self.client.session.rollback() |
| 147 |
raise |
| 148 |
record = None |
| 149 |
|
| 150 |
if record: |
| 151 |
serialized_session_data = want_bytes(record.data) |
| 152 |
return self.serializer.decode(serialized_session_data) |
| 153 |
return None |
| 154 |
|
| 155 |
@retry_query() |
| 156 |
def _delete_session(self, store_id: str) -> None: |
| 157 |
try: |
| 158 |
self.sql_session_model.query.filter_by(session_id=store_id).delete() |
| 159 |
self.client.session.commit() |
| 160 |
except Exception: |
| 161 |
self.client.session.rollback() |
| 162 |
raise |
| 163 |
|
| 164 |
@retry_query() |
| 165 |
def _upsert_session( |
| 166 |
self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str |
| 167 |
) -> None: |
| 168 |
storage_expiration_datetime = datetime.utcnow() + session_lifetime |
| 169 |
|
| 170 |
# Serialize session data |
| 171 |
serialized_session_data = self.serializer.encode(session) |
| 172 |
|
| 173 |
# Update existing or create new session in the database |
| 174 |
try: |
| 175 |
record = self.sql_session_model.query.filter_by(session_id=store_id).first() |
| 176 |
if record: |
| 177 |
record.data = serialized_session_data |
| 178 |
record.expiry = storage_expiration_datetime |
| 179 |
else: |
| 180 |
record = self.sql_session_model( |
| 181 |
session_id=store_id, |
| 182 |
data=serialized_session_data, |
| 183 |
expiry=storage_expiration_datetime, |
| 184 |
) |
| 185 |
self.client.session.add(record) |
| 186 |
self.client.session.commit() |
| 187 |
except Exception: |
| 188 |
self.client.session.rollback() |
| 189 |
raise |