2024-02-19 11:54:13 +00:00
|
|
|
|
import math
|
2023-12-24 14:25:57 +00:00
|
|
|
|
import time
|
2024-02-19 11:45:55 +00:00
|
|
|
|
from functools import wraps
|
2024-02-21 14:55:54 +00:00
|
|
|
|
from sqlalchemy import event, Engine
|
2023-11-22 16:38:39 +00:00
|
|
|
|
from typing import Any, Callable, Dict, TypeVar
|
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
from dogpile.cache import make_region
|
2024-02-21 14:55:54 +00:00
|
|
|
|
from sqlalchemy import Column, Integer, create_engine
|
2021-06-28 09:08:09 +00:00
|
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2023-11-22 16:38:39 +00:00
|
|
|
|
from sqlalchemy.orm import Session
|
2021-06-28 09:08:09 +00:00
|
|
|
|
from sqlalchemy.sql.schema import Table
|
2024-02-20 16:19:46 +00:00
|
|
|
|
from services.logger import root_logger as logger
|
2023-11-22 16:38:39 +00:00
|
|
|
|
from settings import DB_URL
|
2023-11-03 10:10:22 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
# Создание региона кэша с TTL 300 секунд
|
2024-02-21 16:14:58 +00:00
|
|
|
|
cache_region = make_region().configure('dogpile.cache.memory', expiration_time=300)
|
2024-02-19 10:16:44 +00:00
|
|
|
|
|
|
|
|
|
# Подключение к базе данных SQLAlchemy
|
|
|
|
|
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
|
2024-02-21 16:14:58 +00:00
|
|
|
|
T = TypeVar('T')
|
2024-02-19 10:16:44 +00:00
|
|
|
|
REGISTRY: Dict[str, type] = {}
|
|
|
|
|
Base = declarative_base()
|
2023-12-24 14:25:57 +00:00
|
|
|
|
|
2024-02-21 15:07:02 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
# Перехватчики для журнала запросов SQLAlchemy
|
2024-02-21 16:14:58 +00:00
|
|
|
|
@event.listens_for(Engine, 'before_cursor_execute')
|
2023-12-24 14:25:57 +00:00
|
|
|
|
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
2024-02-21 14:55:54 +00:00
|
|
|
|
conn._query_start_time = time.time()
|
2024-02-21 10:47:33 +00:00
|
|
|
|
|
2024-02-21 15:07:02 +00:00
|
|
|
|
|
2024-02-21 16:14:58 +00:00
|
|
|
|
@event.listens_for(Engine, 'after_cursor_execute')
|
2023-12-24 14:25:57 +00:00
|
|
|
|
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
2024-02-21 16:14:58 +00:00
|
|
|
|
if hasattr(conn, '_query_start_time'):
|
2024-02-21 14:55:54 +00:00
|
|
|
|
elapsed = time.time() - conn._query_start_time
|
|
|
|
|
del conn._query_start_time
|
2024-02-21 19:16:29 +00:00
|
|
|
|
if elapsed > 0.9: # Adjust threshold as needed
|
2024-02-21 15:07:02 +00:00
|
|
|
|
logger.debug(
|
2024-02-21 18:47:00 +00:00
|
|
|
|
f"\n{statement}\n{'*' * math.floor(elapsed)} {elapsed:.3f} s"
|
2024-02-21 15:07:02 +00:00
|
|
|
|
)
|
2024-02-21 14:55:54 +00:00
|
|
|
|
|
2022-09-03 10:50:14 +00:00
|
|
|
|
|
2024-02-21 16:14:58 +00:00
|
|
|
|
def local_session(src=''):
|
2023-11-22 16:38:39 +00:00
|
|
|
|
return Session(bind=engine, expire_on_commit=False)
|
|
|
|
|
|
2024-02-21 07:27:16 +00:00
|
|
|
|
|
2021-06-28 09:08:09 +00:00
|
|
|
|
class Base(declarative_base()):
|
2022-09-03 10:50:14 +00:00
|
|
|
|
__table__: Table
|
|
|
|
|
__tablename__: str
|
|
|
|
|
__new__: Callable
|
|
|
|
|
__init__: Callable
|
2023-01-31 07:36:54 +00:00
|
|
|
|
__allow_unmapped__ = True
|
2023-01-31 07:44:06 +00:00
|
|
|
|
__abstract__ = True
|
2024-02-21 16:14:58 +00:00
|
|
|
|
__table_args__ = {'extend_existing': True}
|
2023-01-31 07:44:06 +00:00
|
|
|
|
|
|
|
|
|
id = Column(Integer, primary_key=True)
|
2022-09-03 10:50:14 +00:00
|
|
|
|
|
|
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
|
|
|
REGISTRY[cls.__name__] = cls
|
|
|
|
|
|
|
|
|
|
def dict(self) -> Dict[str, Any]:
|
|
|
|
|
column_names = self.__table__.columns.keys()
|
2024-02-21 16:14:58 +00:00
|
|
|
|
if '_sa_instance_state' in column_names:
|
|
|
|
|
column_names.remove('_sa_instance_state')
|
2023-11-03 10:10:22 +00:00
|
|
|
|
try:
|
|
|
|
|
return {c: getattr(self, c) for c in column_names}
|
|
|
|
|
except Exception as e:
|
2024-02-21 16:14:58 +00:00
|
|
|
|
logger.error(f'Error occurred while converting object to dictionary: {e}')
|
2023-11-03 10:10:22 +00:00
|
|
|
|
return {}
|
2023-11-22 16:38:39 +00:00
|
|
|
|
|
|
|
|
|
def update(self, values: Dict[str, Any]) -> None:
|
|
|
|
|
for key, value in values.items():
|
|
|
|
|
if hasattr(self, key):
|
|
|
|
|
setattr(self, key, value)
|
2024-02-19 10:16:44 +00:00
|
|
|
|
|
2024-02-21 07:27:16 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
# Декоратор для кэширования методов
|
|
|
|
|
def cache_method(cache_key: str):
|
|
|
|
|
def decorator(f):
|
|
|
|
|
@wraps(f)
|
|
|
|
|
def decorated_function(*args, **kwargs):
|
|
|
|
|
# Генерация ключа для кэширования
|
|
|
|
|
key = cache_key.format(*args, **kwargs)
|
|
|
|
|
# Получение значения из кэша
|
|
|
|
|
result = cache_region.get(key)
|
|
|
|
|
if result is None:
|
|
|
|
|
# Если значение отсутствует в кэше, вызываем функцию и кэшируем результат
|
|
|
|
|
result = f(*args, **kwargs)
|
|
|
|
|
cache_region.set(key, result)
|
|
|
|
|
return result
|
2024-02-21 07:27:16 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
return decorated_function
|
2024-02-21 07:27:16 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
return decorator
|