From 1e027d1fd116f35a63d94396572e1bbfc6ae346e Mon Sep 17 00:00:00 2001 From: vvzvlad Date: Sat, 1 Feb 2025 21:17:17 +0300 Subject: [PATCH] Refactor FastAPI server configuration and improve config handling --- api_server.py | 24 +++++++++++++++--------- config.py | 13 +++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/api_server.py b/api_server.py index b8cb615..4508fb8 100644 --- a/api_server.py +++ b/api_server.py @@ -1,23 +1,29 @@ +import logging +import json + +from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, Response from fastapi.responses import HTMLResponse from telegram_client import TelegramClient from config import get_settings -import logging -import json logger = logging.getLogger(__name__) -app = FastAPI(title="PyroTg Bridge") client = TelegramClient() settings = get_settings() -@app.on_event("startup") -async def startup(): +@asynccontextmanager +async def lifespan(_: FastAPI): + # Startup await client.start() - -@app.on_event("shutdown") -async def shutdown(): + yield + # Shutdown await client.stop() +app = FastAPI( + title="PyroTg Bridge", + lifespan=lifespan +) + @app.get("/html/{channel}/{post_id}", response_class=HTMLResponse) async def get_post_html(channel: str, post_id: int): try: @@ -32,7 +38,7 @@ async def get_post_html(channel: str, post_id: int): return post["html"] except Exception as e: logger.error(f"HTML endpoint error: {str(e)}") - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=str(e)) from e @app.get("/json/{channel}/{post_id}") async def get_post(channel: str, post_id: int): diff --git a/config.py b/config.py index a3fc832..dee5dfd 100644 --- a/config.py +++ b/config.py @@ -2,19 +2,12 @@ import os TG_API_ID = int(os.getenv("TG_API_ID")) TG_API_HASH = os.getenv("TG_API_HASH") -SESSION_PATH = os.getenv("SESSION_PATH", "session.file") +SESSION_PATH = os.getenv("SESSION_PATH", "session.file") or "session.file" API_HOST = os.getenv("API_HOST", "0.0.0.0") -API_PORT = int(os.getenv("API_PORT", 8000)) -REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", 30)) +API_PORT = int(os.getenv("API_PORT") or 8000) +REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT") or 30) SESSION_STRING = os.getenv("TG_SESSION_STRING", "") -DEFAULT_CONFIG = { - "session_string": "", - "tg_api_id": 12345, - "tg_api_hash": "xxxxxxxx", - "file_access_flags": ["can_access_files"] -} - def get_settings(): return { "tg_api_id": TG_API_ID,