summaryrefslogtreecommitdiff
path: root/utils/__init__.py
blob: 22d705844ee8a5ee1d56d7b2ee351541c44b0ee9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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