Added comments to Python Code.
This commit is contained in:
1 parent
aa4c5f3681
commit
7bd6b9c4b8
8 files changed
+448
-24
No files matched your search
+44
-3
@@ -1,4 +1,8 @@
|
||||
"""Durable calculation history for PostgreSQL, with a local SQLite fallback."""
|
||||
"""
|
||||
Хранилище истории расчётов.
|
||||
|
||||
Поддержка PostgreSQL (primary) и SQLite (fallback для локальной разработки).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,9 +14,22 @@ from typing import Any
|
||||
|
||||
|
||||
class CalculationStore:
|
||||
"""Persist successful calculations without coupling the domain to a database."""
|
||||
"""
|
||||
Сохраняет успешные расчёты без привязки домена к конкретной БД.
|
||||
|
||||
Поддерживает два режима:
|
||||
- PostgreSQL через psycopg (production)
|
||||
- SQLite через sqlite3 (локальная разработка)
|
||||
"""
|
||||
|
||||
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||
"""
|
||||
Инициализация хранилища с автоматическим созданием схемы.
|
||||
|
||||
Args:
|
||||
database_url: URL PostgreSQL-БД (например postgresql://...)
|
||||
sqlite_path: Путь к локальному SQLite-файлу
|
||||
"""
|
||||
self.database_url = database_url or ""
|
||||
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
||||
fetch_limit = 5000
|
||||
@@ -33,6 +50,7 @@ class CalculationStore:
|
||||
)
|
||||
|
||||
def _ensure_sqlite_schema(self) -> None:
|
||||
"""Создаёт таблицу calculations в SQLite, если её нет."""
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS calculations (
|
||||
@@ -48,6 +66,7 @@ class CalculationStore:
|
||||
)
|
||||
|
||||
def _ensure_postgres_schema(self) -> None:
|
||||
"""Создаёт таблицу belki_calculations в PostgreSQL, если её нет."""
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS belki_calculations (
|
||||
@@ -63,6 +82,18 @@ class CalculationStore:
|
||||
)
|
||||
|
||||
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
|
||||
"""
|
||||
Сохраняет результат расчёта в БД.
|
||||
|
||||
Args:
|
||||
actor_id: ID пользователя (None для автоматических расчётов)
|
||||
source: Источник ("vk", "web", "hook")
|
||||
payload: Исходные данные расчёта
|
||||
response: Результат расчёта
|
||||
|
||||
Returns:
|
||||
ID сохранённой записи
|
||||
"""
|
||||
mode = str(payload.get("mode", response.get("mode", "unknown")))
|
||||
message = str(response["message"])
|
||||
result = response.get("result")
|
||||
@@ -88,7 +119,17 @@ class CalculationStore:
|
||||
|
||||
def list_calculations(self, *, sort_by: str = "escort_id", descending: bool = True,
|
||||
limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""Return admin rows with safe, application-level sorting by participant or kitten."""
|
||||
"""
|
||||
Возвращает записи истории для админ-панели.
|
||||
|
||||
Безопасная сортировка на уровне приложения (не SQL-инъекция):
|
||||
- escort_id, escort_name — по сопровождающему
|
||||
- kitten_id, kitten_name — по котянку
|
||||
|
||||
Ограничения:
|
||||
- fetch_limit: 5000 записей для выборки из БД
|
||||
- limit: 1-500 записей для возврата
|
||||
"""
|
||||
limit = max(1, min(int(limit), 500))
|
||||
fetch_limit = 5000
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
|
||||
Reference in new issue
Block a user