dane w headerach i inne funkcje
This commit is contained in:
49
app/main.py
49
app/main.py
@@ -1,22 +1,61 @@
|
||||
from fastapi import FastAPI, Response
|
||||
from .api import router
|
||||
from fastapi.middleware.base import BaseHTTPMiddleware
|
||||
from fastapi.responses import Response, PlainTextResponse
|
||||
from .deps import get_geo
|
||||
from .api import get_client_ip, router
|
||||
from .config import settings
|
||||
import uvicorn
|
||||
|
||||
app = FastAPI(title='IP Geo API')
|
||||
app = FastAPI(title="IP Geo API")
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
async def add_geo_headers(request, call_next):
|
||||
ip = get_client_ip(request)
|
||||
geo = get_geo()
|
||||
data = geo.lookup(ip)
|
||||
|
||||
response: Response = await call_next(request)
|
||||
|
||||
country = data.get("country", {}).get("name") if data.get("country") else None
|
||||
city = data.get("city")
|
||||
ip_val = data.get("ip")
|
||||
|
||||
if ip_val and country:
|
||||
response.headers["X-IP-ADDRESS"] = ip_val
|
||||
response.headers["X-COUNTRY"] = country
|
||||
if city:
|
||||
response.headers["X-CITY"] = city
|
||||
|
||||
return response
|
||||
|
||||
|
||||
app.add_middleware(BaseHTTPMiddleware, dispatch=add_geo_headers)
|
||||
|
||||
|
||||
@app.get("/favicon.ico")
|
||||
async def favicon():
|
||||
return Response(status_code=204)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@app.get("/")
|
||||
async def root(request: Request):
|
||||
ua = request.headers.get("user-agent", "").lower()
|
||||
ip = get_client_ip(request)
|
||||
|
||||
if any(x in ua for x in ["mozilla", "chrome", "safari", "edge", "firefox"]):
|
||||
return Response(status_code=404)
|
||||
|
||||
return PlainTextResponse(ip)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
'app.main:app',
|
||||
"app.main:app",
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
log_level=settings.log_level,
|
||||
proxy_headers=True,
|
||||
proxy_headers=True,
|
||||
forwarded_allow_ips="*",
|
||||
# access_log=True
|
||||
)
|
||||
|
Reference in New Issue
Block a user