This commit is contained in:
parent
233c71385f
commit
79ec5a1841
|
@ -1,11 +1,8 @@
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
import time
|
import time
|
||||||
|
|
||||||
# from contextlib import contextmanager
|
|
||||||
from typing import Any, Callable, Dict, TypeVar
|
from typing import Any, Callable, Dict, TypeVar
|
||||||
|
|
||||||
# from psycopg2.errors import UniqueViolation
|
|
||||||
from sqlalchemy import Column, Integer, create_engine, event
|
from sqlalchemy import Column, Integer, create_engine, event
|
||||||
from sqlalchemy.engine import Engine
|
from sqlalchemy.engine import Engine
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
@ -15,53 +12,35 @@ from sqlalchemy.sql.schema import Table
|
||||||
from settings import DB_URL
|
from settings import DB_URL
|
||||||
|
|
||||||
|
|
||||||
logging.basicConfig()
|
# Настройка журнала
|
||||||
logger = logging.getLogger('\t [sqlalchemy.profiler]\t')
|
logging.basicConfig(level=logging.DEBUG)
|
||||||
logger.setLevel(logging.DEBUG)
|
|
||||||
|
# Создание обработчика журнала для записи сообщений в файл
|
||||||
|
logger = logging.getLogger('sqlalchemy.profiler')
|
||||||
|
|
||||||
|
|
||||||
@event.listens_for(Engine, 'before_cursor_execute')
|
@event.listens_for(Engine, 'before_cursor_execute')
|
||||||
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||||
conn.info.setdefault('query_start_time', []).append(time.time())
|
conn.info.setdefault('query_start_time', []).append(time.time())
|
||||||
# logger.debug(f" {statement}")
|
|
||||||
|
|
||||||
|
|
||||||
@event.listens_for(Engine, 'after_cursor_execute')
|
@event.listens_for(Engine, 'after_cursor_execute')
|
||||||
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||||
total = time.time() - conn.info['query_start_time'].pop(-1)
|
total = time.time() - conn.info['query_start_time'].pop(-1)
|
||||||
total = math.floor(total * 10000) / 10000
|
total = math.floor(total * 10000) / 10000
|
||||||
if total > 35:
|
if total > 25:
|
||||||
print(f'\n{statement}\n----------------- Finished in {total} s ')
|
logger.debug(f'Long running query: {statement}, Execution Time: {total} s')
|
||||||
|
|
||||||
|
|
||||||
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
|
engine = create_engine(DB_URL, echo=False, pool_size=10, max_overflow=20)
|
||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar('T')
|
||||||
|
|
||||||
REGISTRY: Dict[str, type] = {}
|
REGISTRY: Dict[str, type] = {}
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
# @contextmanager
|
|
||||||
def local_session(src=''):
|
def local_session(src=''):
|
||||||
return Session(bind=engine, expire_on_commit=False)
|
return Session(bind=engine, expire_on_commit=False)
|
||||||
|
|
||||||
# try:
|
|
||||||
# yield session
|
|
||||||
# session.commit()
|
|
||||||
# except Exception as e:
|
|
||||||
# if not (src == "create_shout" and isinstance(e, UniqueViolation)):
|
|
||||||
# import traceback
|
|
||||||
|
|
||||||
# session.rollback()
|
|
||||||
# print(f"[services.db] {src}: {e}")
|
|
||||||
|
|
||||||
# traceback.print_exc()
|
|
||||||
|
|
||||||
# raise Exception("[services.db] exception")
|
|
||||||
|
|
||||||
# finally:
|
|
||||||
# session.close()
|
|
||||||
|
|
||||||
|
|
||||||
class Base(declarative_base()):
|
class Base(declarative_base()):
|
||||||
__table__: Table
|
__table__: Table
|
||||||
|
@ -84,7 +63,7 @@ class Base(declarative_base()):
|
||||||
try:
|
try:
|
||||||
return {c: getattr(self, c) for c in column_names}
|
return {c: getattr(self, c) for c in column_names}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f'[services.db] Error dict: {e}')
|
logger.error(f'Error occurred while converting object to dictionary: {e}')
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def update(self, values: Dict[str, Any]) -> None:
|
def update(self, values: Dict[str, Any]) -> None:
|
||||||
|
|
Loading…
Reference in New Issue
Block a user