From ee7123f38219c99f37c21e92b8cb96e014748b16 Mon Sep 17 00:00:00 2001 From: Stas Medvedev Date: Tue, 11 Jun 2024 01:24:14 +0300 Subject: utils.py, logging.py, log_config.json --- app/logging.py | 9 +++++++++ app/main.py | 36 ++++++------------------------------ app/utils.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 30 deletions(-) create mode 100644 app/logging.py create mode 100644 app/utils.py (limited to 'app') diff --git a/app/logging.py b/app/logging.py new file mode 100644 index 0000000..e24328d --- /dev/null +++ b/app/logging.py @@ -0,0 +1,9 @@ +import logging + + +class RequestFileHandler(logging.FileHandler): + def __init__(self) -> None: + super().__init__('./static/request.log') + + +logger = logging.getLogger('app.request') diff --git a/app/main.py b/app/main.py index 891adb1..d643447 100644 --- a/app/main.py +++ b/app/main.py @@ -1,10 +1,10 @@ -from pathlib import Path - from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from starlette.templating import Jinja2Templates -import httpx + +from app.utils import get_avatar_urls, get_client_geo, get_client_host +from app.logging import logger templates = Jinja2Templates(directory="templates") @@ -12,35 +12,11 @@ app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") -def get_avatar_urls(): - path = Path('./static') / 'avatars' - if not path.exists(): - path.mkdir() - - return sorted([ - str(jpg_avatar) - for jpg_avatar - in path.glob('*.jpg') - ]) - - -def get_client_host(request: Request): - return request.client.host - - -async def get_client_geo(client_host: str): - async with httpx.AsyncClient() as client: - response = await client.get( - # использование https платная опция сервиса, инфо тут https://members.ip-api.com/ - url='http://ip-api.com/json/{}'.format(client_host), - params={"lang": "ru"} - ) - data = response.json() - return data - - @app.get("/", response_class=HTMLResponse) async def index(request: Request): + + logger.info(str(dict(request.headers))) + return templates.TemplateResponse( "index.html", { diff --git a/app/utils.py b/app/utils.py new file mode 100644 index 0000000..08373e0 --- /dev/null +++ b/app/utils.py @@ -0,0 +1,31 @@ +from pathlib import Path +from fastapi import Request +import httpx + + +def get_avatar_urls(): + path = Path('./static') / 'avatars' + if not path.exists(): + path.mkdir() + + return sorted([ + str(jpg_avatar) + for jpg_avatar + in path.glob('*.jpg') + ]) + + +def get_client_host(request: Request): + return request.client.host + + +async def get_client_geo(client_host: str): + async with httpx.AsyncClient() as client: + response = await client.get( + # использование https платная опция сервиса, инфо тут https://members.ip-api.com/ + url='http://ip-api.com/json/{}'.format(client_host), + params={"lang": "ru"} + ) + data = response.json() + return data + -- cgit v1.2.3