Files
duty-teller/db/session.py
Nikolay Tatarinov 1948618394 Refactor configuration and enhance Telegram initData validation
- Improved formatting and readability in config.py and other files by adding line breaks.
- Introduced INIT_DATA_MAX_AGE_SECONDS to enforce replay protection for Telegram initData.
- Updated validate_init_data function to include max_age_seconds parameter for validation.
- Enhanced API to reject old initData based on the new max_age_seconds setting.
- Added tests for auth_date expiry and validation of initData in test_telegram_auth.py.
- Updated README with details on the new INIT_DATA_MAX_AGE_SECONDS configuration.
2026-02-17 17:31:20 +03:00

47 lines
1.2 KiB
Python

"""SQLAlchemy engine and session factory."""
from contextlib import contextmanager
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
_engine = None
_SessionLocal = None
@contextmanager
def session_scope(database_url: str) -> Generator[Session, None, None]:
"""Context manager: yields a session and closes it on exit."""
session = get_session(database_url)
try:
yield session
finally:
session.close()
def get_engine(database_url: str):
global _engine
if _engine is None:
_engine = create_engine(
database_url,
connect_args={"check_same_thread": False}
if "sqlite" in database_url
else {},
echo=False,
)
return _engine
def get_session_factory(database_url: str) -> sessionmaker[Session]:
global _SessionLocal
if _SessionLocal is None:
engine = get_engine(database_url)
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
return _SessionLocal
def get_session(database_url: str) -> Session:
return get_session_factory(database_url)()