| 1 |
import time |
| 2 |
import warnings |
| 3 |
from datetime import timedelta as TimeDelta |
| 4 |
from typing import Any, Optional, Protocol |
| 5 |
|
| 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 MemcacheClientProtocol(Protocol): |
| 14 |
def get(self, key: str) -> Optional[Any]: ... |
| 15 |
def set(self, key: str, value: Any, timeout: int) -> bool: ... |
| 16 |
def delete(self, key: str) -> bool: ... |
| 17 |
|
| 18 |
|
| 19 |
class MemcachedSession(ServerSideSession): |
| 20 |
pass |
| 21 |
|
| 22 |
|
| 23 |
class MemcachedSessionInterface(ServerSideSessionInterface): |
| 24 |
"""A Session interface that uses memcached as session storage. (`pylibmc`, `libmc`, `python-memcached` or `pymemcache` required) |
| 25 |
|
| 26 |
:param client: A ``memcache.Client`` instance. |
| 27 |
:param key_prefix: A prefix that is added to all storage keys. |
| 28 |
:param use_signer: Whether to sign the session id cookie or not. |
| 29 |
:param permanent: Whether to use permanent session or not. |
| 30 |
:param sid_length: The length of the generated session id in bytes. |
| 31 |
:param serialization_format: The serialization format to use for the session data. |
| 32 |
|
| 33 |
.. versionadded:: 0.7 |
| 34 |
The `serialization_format` and `app` parameters were added. |
| 35 |
|
| 36 |
.. versionadded:: 0.6 |
| 37 |
The `sid_length` parameter was added. |
| 38 |
|
| 39 |
.. versionadded:: 0.2 |
| 40 |
The `use_signer` parameter was added. |
| 41 |
""" |
| 42 |
|
| 43 |
serializer = ServerSideSessionInterface.serializer |
| 44 |
session_class = MemcachedSession |
| 45 |
ttl = True |
| 46 |
|
| 47 |
def __init__( |
| 48 |
self, |
| 49 |
app: Flask, |
| 50 |
client: Optional[MemcacheClientProtocol] = Defaults.SESSION_MEMCACHED, |
| 51 |
key_prefix: str = Defaults.SESSION_KEY_PREFIX, |
| 52 |
use_signer: bool = Defaults.SESSION_USE_SIGNER, |
| 53 |
permanent: bool = Defaults.SESSION_PERMANENT, |
| 54 |
sid_length: int = Defaults.SESSION_ID_LENGTH, |
| 55 |
serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT, |
| 56 |
): |
| 57 |
if client is None or not all( |
| 58 |
hasattr(client, method) for method in ["get", "set", "delete"] |
| 59 |
): |
| 60 |
warnings.warn( |
| 61 |
"No valid memcache.Client instance provided, attempting to create a new instance on localhost with default settings.", |
| 62 |
RuntimeWarning, |
| 63 |
stacklevel=1, |
| 64 |
) |
| 65 |
client = self._get_preferred_memcache_client() |
| 66 |
self.client = client |
| 67 |
super().__init__( |
| 68 |
app, key_prefix, use_signer, permanent, sid_length, serialization_format |
| 69 |
) |
| 70 |
|
| 71 |
def _get_preferred_memcache_client(self): |
| 72 |
clients = [ |
| 73 |
("pylibmc", ["127.0.0.1:11211"]), |
| 74 |
("memcache", ["127.0.0.1:11211"]), # python-memcached |
| 75 |
("pymemcache.client.base", "127.0.0.1:11211"), |
| 76 |
("libmc", ["localhost:11211"]), |
| 77 |
] |
| 78 |
|
| 79 |
for module_name, server in clients: |
| 80 |
try: |
| 81 |
module = __import__(module_name) |
| 82 |
ClientClass = module.Client |
| 83 |
return ClientClass(server) |
| 84 |
except ImportError: |
| 85 |
continue |
| 86 |
|
| 87 |
raise ImportError("No memcache module found") |
| 88 |
|
| 89 |
def _get_memcache_timeout(self, timeout: int) -> int: |
| 90 |
""" |
| 91 |
Memcached deals with long (> 30 days) timeouts in a special |
| 92 |
way. Call this function to obtain a safe value for your timeout. |
| 93 |
""" |
| 94 |
if timeout > 2592000: # 60*60*24*30, 30 days |
| 95 |
# Switch to absolute timestamps. |
| 96 |
timeout += int(time.time()) |
| 97 |
return timeout |
| 98 |
|
| 99 |
def _retrieve_session_data(self, store_id: str) -> Optional[dict]: |
| 100 |
# Get the saved session (item) from the database |
| 101 |
serialized_session_data = self.client.get(store_id) |
| 102 |
if serialized_session_data: |
| 103 |
return self.serializer.decode(serialized_session_data) |
| 104 |
return None |
| 105 |
|
| 106 |
def _delete_session(self, store_id: str) -> None: |
| 107 |
self.client.delete(store_id) |
| 108 |
|
| 109 |
def _upsert_session( |
| 110 |
self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str |
| 111 |
) -> None: |
| 112 |
storage_time_to_live = total_seconds(session_lifetime) |
| 113 |
|
| 114 |
# Serialize the session data |
| 115 |
serialized_session_data = self.serializer.encode(session) |
| 116 |
|
| 117 |
# Update existing or create new session in the database |
| 118 |
self.client.set( |
| 119 |
store_id, |
| 120 |
serialized_session_data, |
| 121 |
self._get_memcache_timeout(storage_time_to_live), |
| 122 |
) |