FastAPI (Python)
FastAPI wurde für leistungsstarke, asynchrone Webanwendungen entwickelt. Um diese Geschwindigkeit aufrechtzuerhalten, integrieren wir ProxyTracer mit einer benutzerdefiniertenBaseHTTPMiddleware und einem asynchronen HTTP-Client (httpx), um sicherzustellen, dass die Ereignisschleife niemals blockiert wird.
Die Middleware
Diese Implementierung extrahiert sicher die echte Client-IP, verwendet einen asynchronen Verbindungspool zur Abfrage von ProxyTracer und gibt ein strenges 403 Forbidden zurück, wenn das proxy-Flag true ist.
import os
import httpx
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
app = FastAPI()
class ProxyTracerMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
self.api_key = os.getenv("PROXYTRACER_API_KEY")
# Initialize a persistent async client for connection pooling and raw speed
self.client = httpx.AsyncClient(timeout=0.5) # Strict 500ms timeout
async def dispatch(self, request: Request, call_next):
# 1. Safely extract the real IP behind load balancers/proxies
forwarded_for = request.headers.get("x-forwarded-for")
if forwarded_for:
ip = forwarded_for.split(",")[0].strip()
else:
ip = request.client.host if request.client else None
# Skip local development IPs
if ip and ip not in ["127.0.0.1", "::1", "testclient"]:
try:
# 2. Query ProxyTracer API asynchronously
response = await self.client.get(
f"https://api.proxytracer.com/v1/check/{ip}",
headers={"Authorization": f"Bearer {self.api_key}"}
)
if response.status_code == 200:
data = response.json()
# 3. Drop the connection immediately if a proxy is detected
if data.get("proxy") is True:
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"error": "Access Denied: VPN or Proxy detected."}
)
except httpx.RequestError as e:
# Fail open: Log the network error and allow the request to proceed
print(f"ProxyTracer API timeout or failure: {e}")
# 4. Traffic is clean, proceed to the route handler
return await call_next(request)
# Apply the middleware globally
app.add_middleware(ProxyTracerMiddleware)Hinweis zur Abhängigkeit: Diese Implementierung erfordert die httpx-Bibliothek für asynchrone HTTP-Anforderungen. Installieren Sie sie über pip install httpx.
Last updated on