From 2e50db236fa5d922bf18061140e497d6c5d0237c Mon Sep 17 00:00:00 2001 From: Medvedev Stanislav Date: Sun, 9 Jun 2024 22:17:30 +0300 Subject: =?UTF-8?q?client=5Fgeo=20=D0=BD=D0=B0=20html=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=86=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 16 ++++++++++++++++ app/main.py | 28 ++++++++++++++++++++++++++-- templates/index.html | 8 +++++++- 3 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..f85c840 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "uvicorn", + "type": "debugpy", + "request": "launch", + "module": "uvicorn", + "args": ["app.main:app", "--host", "0.0.0.0"], + "console": "integratedTerminal" + } + ] +} \ No newline at end of file diff --git a/app/main.py b/app/main.py index 1c4590e..d9ea01c 100644 --- a/app/main.py +++ b/app/main.py @@ -1,12 +1,36 @@ from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from starlette.templating import Jinja2Templates +import httpx app = FastAPI() templates = Jinja2Templates(directory="templates") +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 read_root(request: Request): - return templates.TemplateResponse("index.html", {"request": request}) +async def index(request: Request): + return templates.TemplateResponse( + "index.html", + { + "request": request, + "client_geo": await get_client_geo( + get_client_host(request) + ) + } + ) diff --git a/templates/index.html b/templates/index.html index c254629..a2e6d0b 100644 --- a/templates/index.html +++ b/templates/index.html @@ -3,9 +3,15 @@ + Document - Привет мир + Привет + {% if 'city' in client_geo %} +

{{client_geo['country']}}

+

{{client_geo['city']}}

+

{{client_geo['query']}}

+ {% endif %} \ No newline at end of file -- cgit v1.2.3