summaryrefslogtreecommitdiff
path: root/utils/__init__.py
blob: 3f41882a2f869bc20267044939e6f114af9a4b6c (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
33
34
35
36
37
38
39
40
41
from pathlib import Path
from typing import Annotated

from fastapi import Request, Header, Depends
import httpx

from . import restricted_exec

__all__ = [
    'restricted_exec',
    'get_avatar_urls',
    'get_client_host',
    'get_client_geo'
]


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