summaryrefslogtreecommitdiff
path: root/app/main.py
blob: 891adb1aa412404a094e2626eaab387e8ab972e3 (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
42
43
44
45
46
47
48
49
50
51
52
53
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

templates = Jinja2Templates(directory="templates")

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):
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            "client_geo": await get_client_geo(
                get_client_host(request)
            ),
            "avatar_urls": get_avatar_urls()
        }
    )