diff --git a/Makefile b/Makefile index 7464e91..282c75b 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,22 @@ run: source ./venv/bin/activate && uvicorn --reload --log-config logging_test.conf social.routes.base:app +format: configure + source ./venv/bin/activate && autoflake -r --in-place --remove-all-unused-imports ./auth_backend + source ./venv/bin/activate && isort ./auth_backend + source ./venv/bin/activate && black ./auth_backend + +configure: venv + source ./venv/bin/activate && pip install -r requirements.dev.txt -r requirements.txt + +venv: + python3.11 -m venv venv + db: docker run -d -p 5432:5432 -e POSTGRES_HOST_AUTH_METHOD=trust --name db-social postgres:15 - sleep 3 migrate: - alembic upgrade head + source ./venv/bin/activate && alembic upgrade head + +test: + source ./venv/bin/activate && python3 -m pytest --verbosity=2 --showlocals --log-level=DEBUG diff --git a/migrations/env.py b/migrations/env.py index 6d7a4ce..ad3e7ef 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -61,7 +61,7 @@ def run_migrations_online(): """ configuration = config.get_section(config.config_ini_section) - configuration['sqlalchemy.url'] = settings.DB_DSN + configuration['sqlalchemy.url'] = str(settings.DB_DSN) connectable = engine_from_config( configuration, prefix="sqlalchemy.", diff --git a/requirements.dev.txt b/requirements.dev.txt index 5f3e211..34a2d44 100644 --- a/requirements.dev.txt +++ b/requirements.dev.txt @@ -1,3 +1,4 @@ +autoflake black httpx pytest diff --git a/requirements.txt b/requirements.txt index 2411bae..24155fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,6 +2,7 @@ fastapi fastapi-sqlalchemy psycopg2-binary pydantic[dotenv] +pydantic-settings uvicorn alembic SQLAlchemy diff --git a/social/routes/base.py b/social/routes/base.py index 898e7e9..e46de7a 100644 --- a/social/routes/base.py +++ b/social/routes/base.py @@ -13,11 +13,8 @@ settings = get_settings() app = FastAPI( title='Сервис мониторинга активности', - description=( - 'Серверная часть сервиса для выдачи печенек за активности' - ), + description=('Серверная часть сервиса для выдачи печенек за активности'), version=__version__, - # Настраиваем интернет документацию root_path=settings.ROOT_PATH if __version__ != 'dev' else '/', docs_url=None if __version__ != 'dev' else '/docs', @@ -28,7 +25,7 @@ app.add_middleware( DBSessionMiddleware, - db_url=settings.DB_DSN, + db_url=str(settings.DB_DSN), engine_args={"pool_pre_ping": True, "isolation_level": "AUTOCOMMIT"}, ) diff --git a/social/settings.py b/social/settings.py index d229f89..c8a0ab6 100644 --- a/social/settings.py +++ b/social/settings.py @@ -1,12 +1,15 @@ import os -from pydantic import BaseSettings, PostgresDsn +from pydantic import ConfigDict, PostgresDsn +from pydantic_settings import BaseSettings from functools import lru_cache class Settings(BaseSettings): """Application settings""" + model_config = ConfigDict(case_sensitive=True, env_file=".env", extra="allow") + DB_DSN: PostgresDsn = 'postgresql://postgres@localhost:5432/postgres' ROOT_PATH: str = '/' + os.getenv('APP_NAME', '') @@ -15,13 +18,7 @@ class Settings(BaseSettings): CORS_ALLOW_METHODS: list[str] = ['*'] CORS_ALLOW_HEADERS: list[str] = ['*'] - TELEGRAM_BOT_TOKEN: str | None - - class Config: - """Pydantic BaseSettings config""" - - case_sensitive = True - env_file = ".env" + TELEGRAM_BOT_TOKEN: str | None = None @lru_cache diff --git a/social/telegram/base.py b/social/telegram/base.py index 0366f29..2b92a6e 100644 --- a/social/telegram/base.py +++ b/social/telegram/base.py @@ -33,9 +33,11 @@ async def send_help(update: Update, context: CustomContext): await context.bot.send_message( chat_id=update.effective_message.chat.id, reply_to_message_id=update.effective_message.id, - text=dedent(""" + text=dedent( + """ Привет, я ответственный за печеньки! Моя основная цель – помогать различным комьюнити расти - """), + """ + ), parse_mode='markdown', ) diff --git a/social/telegram/handlers_viribus.py b/social/telegram/handlers_viribus.py index 871db8b..144c10b 100644 --- a/social/telegram/handlers_viribus.py +++ b/social/telegram/handlers_viribus.py @@ -15,9 +15,7 @@ MessageHandler, CommandHandler, ) -from telegram.ext.filters import ( - Chat -) +from telegram.ext.filters import Chat from social.settings import get_settings from social.telegram.utils import CustomContext @@ -37,6 +35,7 @@ """ ] + def register_handlers(app: Application): app.add_handler(CommandHandler(filters=Chat(CHAT_ID), callback=change_slug, command="slug")) app.add_handler(MessageHandler(filters=Chat(CHAT_ID), callback=delete_system_message)) @@ -49,9 +48,7 @@ async def delete_system_message(update: Update, context: CustomContext): await context.bot.send_message( chat_id=CHAT_ID, message_thread_id=MAIN_TOPIC_ID, - text=dedent(choice(GREETINGS)).format( - name=user.name, id=user.id - ), + text=dedent(choice(GREETINGS)).format(name=user.name, id=user.id), parse_mode='markdown', ) logger.info(f"User {user.name} greeting sent") @@ -69,11 +66,13 @@ async def change_slug(update: Update, context: CustomContext): await context.bot.send_message( chat_id=update.effective_message.chat.id, reply_to_message_id=update.effective_message.id, - text=dedent(""" + text=dedent( + """ Эта команда меняет текст, который пишется справа от имени пользователя в этом чате Текст толжен содержать только буквы, цифры, пробелы и некоторую пунктуацию, не более 16 символов Напиши `/slug текст` для применения - """), + """ + ), parse_mode='markdown', ) return diff --git a/social/telegram/utils.py b/social/telegram/utils.py index 5861e13..7023632 100644 --- a/social/telegram/utils.py +++ b/social/telegram/utils.py @@ -14,6 +14,7 @@ class WebhookUpdate: user_id: int payload: str + class CustomContext(CallbackContext[ExtBot, dict, dict, dict]): """ Custom CallbackContext class that makes `user_data` available for updates of type