2024-01-25 19:41:27 +00:00
|
|
|
|
import logging
|
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
|
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
|
2023-12-24 14:25:57 +00:00
|
|
|
|
from sqlalchemy import Column, Integer, create_engine, event
|
2024-01-25 19:41:27 +00:00
|
|
|
|
from sqlalchemy.engine import 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
|
|
|
|
|
|
2023-11-22 16:38:39 +00:00
|
|
|
|
from settings import DB_URL
|
2023-11-03 10:10:22 +00:00
|
|
|
|
|
2024-02-16 09:16:00 +00:00
|
|
|
|
# Настройка журнала
|
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
2024-02-19 10:16:44 +00:00
|
|
|
|
logger = logging.getLogger('[services.db]')
|
2024-02-19 08:10:12 +00:00
|
|
|
|
logger.setLevel(logging.DEBUG)
|
2024-02-16 09:16:00 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
# Создание региона кэша с TTL 300 секунд
|
|
|
|
|
cache_region = make_region().configure(
|
|
|
|
|
'dogpile.cache.memory',
|
|
|
|
|
expiration_time=300
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Подключение к базе данных SQLAlchemy
|
|
|
|
|
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
|
|
|
|
|
T = TypeVar('T')
|
|
|
|
|
REGISTRY: Dict[str, type] = {}
|
|
|
|
|
Base = declarative_base()
|
2023-12-24 14:25:57 +00:00
|
|
|
|
|
2024-02-19 10:16:44 +00:00
|
|
|
|
# Перехватчики для журнала запросов SQLAlchemy
|
2024-01-25 19:41:27 +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-01-25 19:41:27 +00:00
|
|
|
|
conn.info.setdefault('query_start_time', []).append(time.time())
|
2024-02-19 10:25:47 +00:00
|
|
|
|
logger.debug(f"\n{statement}")
|
2023-12-24 14:25:57 +00:00
|
|
|
|
|
2024-01-25 19:41:27 +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-01-25 19:41:27 +00:00
|
|
|
|
total = time.time() - conn.info['query_start_time'].pop(-1)
|
2024-02-19 11:54:13 +00:00
|
|
|
|
stars = '*' * math.floor(total*1000)
|
2024-02-20 14:27:30 +00:00
|
|
|
|
if stars:
|
|
|
|
|
logger.debug(f' {stars} {total*1000} s\n')
|
2022-09-03 10:50:14 +00:00
|
|
|
|
|
2024-01-25 19:41:27 +00:00
|
|
|
|
def local_session(src=''):
|
2023-11-22 16:38:39 +00:00
|
|
|
|
return Session(bind=engine, expire_on_commit=False)
|
|
|
|
|
|
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-01-25 19:41:27 +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-01-25 19:41:27 +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-16 09:16:00 +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
|
|
|
|
|
|
|
|
|
# Декоратор для кэширования методов
|
|
|
|
|
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
|
|
|
|
|
return decorated_function
|
|
|
|
|
return decorator
|