Files
duty-teller/db/session.py
Nikolay Tatarinov 5dc8c8f255 Enhance API and configuration for Telegram miniapp
- Added support for CORS origins and a new environment variable for miniapp access control.
- Implemented date validation for API requests to ensure correct date formats.
- Updated FastAPI app to allow access without Telegram initData for local development.
- Enhanced error handling and logging for better debugging.
- Added tests for API functionality and Telegram initData validation.
- Updated README with new environment variable details and testing instructions.
- Modified Docker and Git ignore files to include additional directories and files.
2026-02-17 17:21:35 +03:00

45 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
from db.models import Base
_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)()