import requests import json import logging import time import aiohttp from fastapi import FastAPI, Header, Request, Query, HTTPException from fastapi.responses import JSONResponse from contextlib import asynccontextmanager logging.basicConfig(level=logging.INFO) @asynccontextmanager async def lifespan(_app: FastAPI): async with aiohttp.ClientSession( "https://ip.shronk.tech", connector=aiohttp.TCPConnector(limit=2048) ) as client: _app.state.session = client yield app = FastAPI(lifespan=lifespan) app.state.cache = {} @app.get("/") async def ip( request: Request, X_Forwarded_For: str = Header(None), User_Agent: str = Header("Mozilla/5.0"), Accept: str = Header("text/plain"), Accept_Language: str = Header("en-us"), lookup: str = Query(None), ): if lookup: ip = lookup elif X_Forwarded_For: ip = X_Forwarded_For else: ip = request.client.host if ip in app.state.cache: data, timestamp = app.state.cache[ip] if time.time() - timestamp < 3600: logging.info("cache hit for %s", ip) return JSONResponse(data) logging.info("cache expired for %s", ip) logging.info("looking up IP info for %s", ip) try: async with app.state.session.get(f"/lookup?ip={ip}") as response: response.raise_for_status() data = await response.json() except Exception as e: logging.error("Failed to get data for %s: %s", ip, e, exc_info=True) raise HTTPException(500, "Failed to get upstream data.") except json.JSONDecodeError as e: logging.error("Failed to parse data for %s: %s", ip, e, exc_info=True) raise HTTPException(500, "Failed to parse upstream response.") logging.info("%s -> %r", ip, data) data["ip"] = ip data.pop("legalese", None) data.pop("source", None) data.pop("brexitRequired", None) if response.status_code == 200: app.state.cache[ip] = [data, time.time()] return JSONResponse(data, response.status_code)