ЛР2: PostgreSQL, сессии (Basic + Bearer), Compose, миграции
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# Корень проекта (в контейнере код лежит в /app, и это будет "/").
|
||||
BASE_DIR = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class RunConfig(BaseModel):
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8080
|
||||
graceful_timeout: int = 5
|
||||
|
||||
|
||||
class LoggingConfig(BaseModel):
|
||||
level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
|
||||
format: str = "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s"
|
||||
datefmt: str = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
|
||||
class DatabaseConfig(BaseModel):
|
||||
# Значения по умолчанию — для запуска внутри Compose.
|
||||
host: str = "postgres"
|
||||
port: int = 5432
|
||||
name: str = "messenger"
|
||||
user: str = "messenger"
|
||||
password_file: Path = Path("/run/secrets/postgres_password")
|
||||
|
||||
pool_size: int = 5
|
||||
max_overflow: int = 5
|
||||
pool_timeout: int = 5
|
||||
connect_timeout: int = 3
|
||||
statement_timeout_ms: int = 5000
|
||||
echo: bool = False
|
||||
|
||||
def read_password(self) -> str:
|
||||
return read_secret(self.password_file)
|
||||
|
||||
|
||||
class JWTConfig(BaseModel):
|
||||
# Ключ должен сохраняться между перезапусками, иначе выданные токены станут недействительны.
|
||||
secret_file: Path = Path("/run/secrets/jwt_secret")
|
||||
algorithm: str = "HS256"
|
||||
session_ttl_seconds: int = 3600
|
||||
|
||||
def read_secret_key(self) -> str:
|
||||
return read_secret(self.secret_file)
|
||||
|
||||
|
||||
def read_secret(path: Path) -> str:
|
||||
"""Прочитать файл-секрет. Относительный путь считается от корня проекта."""
|
||||
full_path = path if path.is_absolute() else BASE_DIR / path
|
||||
return full_path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
class ApiV1Prefix(BaseModel):
|
||||
prefix: str = "/v1"
|
||||
users: str = "/users"
|
||||
chats: str = "/chats"
|
||||
auth: str = "/auth"
|
||||
|
||||
|
||||
class ApiPrefix(BaseModel):
|
||||
prefix: str = "/api"
|
||||
v1: ApiV1Prefix = ApiV1Prefix()
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=BASE_DIR / ".env",
|
||||
case_sensitive=False,
|
||||
env_nested_delimiter="__",
|
||||
env_prefix="APP_CONFIG__",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
run: RunConfig = RunConfig()
|
||||
api: ApiPrefix = ApiPrefix()
|
||||
logging: LoggingConfig = LoggingConfig()
|
||||
db: DatabaseConfig = DatabaseConfig()
|
||||
jwt: JWTConfig = JWTConfig()
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,57 @@
|
||||
from collections.abc import Iterator
|
||||
|
||||
from sqlalchemy import URL, create_engine, text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from core.config import settings
|
||||
from core.logger import logger
|
||||
|
||||
|
||||
def build_url() -> URL:
|
||||
return URL.create(
|
||||
drivername="postgresql+psycopg",
|
||||
username=settings.db.user,
|
||||
password=settings.db.read_password(),
|
||||
host=settings.db.host,
|
||||
port=settings.db.port,
|
||||
database=settings.db.name,
|
||||
)
|
||||
|
||||
|
||||
engine = create_engine(
|
||||
build_url(),
|
||||
pool_size=settings.db.pool_size,
|
||||
max_overflow=settings.db.max_overflow,
|
||||
pool_timeout=settings.db.pool_timeout,
|
||||
# Проверять соединение перед выдачей из пула (нужно после рестарта PostgreSQL).
|
||||
pool_pre_ping=True,
|
||||
connect_args={
|
||||
"connect_timeout": settings.db.connect_timeout,
|
||||
"options": f"-c statement_timeout={settings.db.statement_timeout_ms}",
|
||||
},
|
||||
echo=settings.db.echo,
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
|
||||
def get_db() -> Iterator[Session]:
|
||||
"""Одна ORM-сессия на HTTP-запрос."""
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
def check_database() -> bool:
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except SQLAlchemyError as exc:
|
||||
# Только тип ошибки: в тексте может оказаться адрес БД.
|
||||
logger.warning(f"PostgreSQL недоступен: {type(exc).__name__}")
|
||||
return False
|
||||
|
||||
|
||||
def log_database_target():
|
||||
logger.info(f"База данных: {engine.url.render_as_string(hide_password=True)}")
|
||||
@@ -0,0 +1,15 @@
|
||||
import logging
|
||||
|
||||
from core.config import settings
|
||||
|
||||
|
||||
def setup_logger():
|
||||
logging.basicConfig(
|
||||
level=settings.logging.level,
|
||||
format=settings.logging.format,
|
||||
datefmt=settings.logging.datefmt,
|
||||
)
|
||||
return logging.getLogger("messenger")
|
||||
|
||||
|
||||
logger = setup_logger()
|
||||
Reference in New Issue
Block a user