FEATURE 9 and 12: cache and refactoring
- из админ_командс убрана работа с БД и шелве - добавлен кеш, он загружается при старте сервиса и обновляется при изменениях, все запросы (антиспам, цитаты) идут уже через него, в БД лишний раз не ходим. В дальнейшем работаем только с ним везде через функции-хелперы - созданы хелперы для создания/удаления цитат и чатов - добавлено выражение в спам-лист (вчера пропустило) - добавлены тесты на спам(выше) и админ_коммандс
This commit is contained in:
+60
-6
@@ -1,4 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Type
|
||||
|
||||
from sqlalchemy import Column, String, Integer, Boolean, ForeignKey
|
||||
from sqlalchemy import create_engine
|
||||
@@ -51,27 +54,78 @@ class Chat(Base):
|
||||
return f'Chat({self.chat_id=}, {self.title=})'
|
||||
|
||||
|
||||
CACHE: dict[int, Type[Chat]] = {}
|
||||
|
||||
|
||||
def _fill_cache():
|
||||
if os.environ.get("testing", "FALSE") == "FALSE":
|
||||
for chat in session.query(Chat).all():
|
||||
CACHE[chat.chat_id] = chat
|
||||
|
||||
|
||||
def is_antispam_enabled(chat_id: int) -> bool:
|
||||
try:
|
||||
return session.query(Chat.antispam).filter_by(chat_id=chat_id).first()[0]
|
||||
except TypeError:
|
||||
if chat_id not in CACHE:
|
||||
return False
|
||||
return CACHE[chat_id].antispam
|
||||
|
||||
|
||||
def is_quote_in_chat(text: str, chat_id: int) -> bool:
|
||||
result = session.query(Quote.text).filter_by(text=text, chat_id=chat_id).first()
|
||||
return bool(result)
|
||||
return text in all_chat_quotes(chat_id)
|
||||
|
||||
|
||||
def delete_quote_in_chat(text: str, chat_id: int):
|
||||
session.execute(delete(Quote).filter_by(text=text, chat_id=chat_id))
|
||||
session.commit()
|
||||
_reload_chat(chat_id)
|
||||
|
||||
|
||||
def all_chat_quotes(chat_id: int) -> list:
|
||||
return session.query(Quote.text).filter(Quote.chat_id == chat_id).all()
|
||||
if chat_id not in CACHE:
|
||||
return []
|
||||
return [quote.text for quote in CACHE[chat_id].quotes]
|
||||
|
||||
|
||||
def is_chat_exists(chat_id: int) -> bool:
|
||||
return chat_id in CACHE
|
||||
|
||||
|
||||
def add_quote(chat_id: int, text: str):
|
||||
session.add(Quote(chat_id=chat_id, text=text))
|
||||
session.commit()
|
||||
_reload_chat(chat_id)
|
||||
|
||||
|
||||
def chat_by_id(chat_id: int) -> None | Chat:
|
||||
return CACHE.get(chat_id)
|
||||
|
||||
|
||||
def add_chat(chat_id: int, chat_title: str):
|
||||
session.add(Chat(chat_id=chat_id, title=chat_title, antispam=1, report=0, reminder=1))
|
||||
session.commit()
|
||||
_reload_chat(chat_id)
|
||||
|
||||
|
||||
def update_chat(chat_id: int, antispam: int = 1, rep: int = 0, rem: int = 1):
|
||||
session.query(Chat).filter_by(chat_id=chat_id).update({"antispam": antispam, "report": rep, "reminder": rem})
|
||||
session.commit()
|
||||
_reload_chat(chat_id)
|
||||
|
||||
|
||||
def delete_chat(chat_id: int) -> str:
|
||||
"""
|
||||
Удаляем чат из БД вместе с его цитатами, возвращаем его название для логирования
|
||||
"""
|
||||
chat = session.query(Chat).filter_by(chat_id=chat_id).first()
|
||||
session.delete(chat)
|
||||
session.commit()
|
||||
del CACHE[chat_id]
|
||||
return chat.title
|
||||
|
||||
|
||||
def _reload_chat(chat_id: int):
|
||||
chat = session.query(Chat).filter(Chat.chat_id == chat_id).first()
|
||||
CACHE[chat_id] = chat
|
||||
|
||||
|
||||
_fill_cache()
|
||||
logging.warning("[START] Load data from db to cache")
|
||||
|
||||
Reference in New Issue
Block a user