Files
mtusi2026lab3/sessions.py
2026-11-04 16:11:13 +03:00

44 lines
1.2 KiB
Python

import os
import redis
class SessionStore:
def __init__(self, url, connect_timeout=2.0, socket_timeout=2.0):
self._url = url
self._client = redis.from_url(
url,
decode_responses=True,
socket_connect_timeout=connect_timeout,
socket_timeout=socket_timeout,
health_check_interval=30,
)
self._prefix = 'sess:'
@classmethod
def from_env(cls):
url = _read_config('CACHE_URL_FILE', 'CACHE_URL')
if not url:
raise RuntimeError('CACHE_URL or CACHE_URL_FILE is required when SESSION_STORE=redis')
return cls(url)
def ping(self):
return self._client.ping()
def create(self, token, user_id, ttl_seconds):
self._client.setex(self._prefix + token, ttl_seconds, user_id)
def get_user_id(self, token):
return self._client.get(self._prefix + token)
def revoke(self, token):
return self._client.delete(self._prefix + token) > 0
def _read_config(file_env, value_env):
path = os.environ.get(file_env)
if path and os.path.isfile(path):
with open(path, encoding='utf-8') as handle:
return handle.read().strip()
return os.environ.get(value_env, '').strip()