From ed49bb17b9e93a1406ab51f7dca5906661863627 Mon Sep 17 00:00:00 2001 From: Stas Medvedev Date: Wed, 12 Jun 2024 16:05:12 +0300 Subject: refactore utils refactore html about, client_geo --- utils/__init__.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 utils/__init__.py (limited to 'utils') diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..22d7058 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1,32 @@ +from pathlib import Path +from typing import Annotated + +from fastapi import Request, Header, Depends +import httpx + + +def get_avatar_urls() -> list[str]: + 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, x_real_ip: Annotated[str | None, Header()] = None +) -> str: + if x_real_ip: + return x_real_ip + return request.client.host + + +async def get_client_geo(client_host: Annotated[str, Depends(get_client_host)]) -> dict: + 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