FastAPI (Python)
FastAPI, yüksek performanslı ve asenkron web uygulamaları için tasarlanmıştır. Bu hızı korumak için, event loop'un hiçbir zaman engellenmemesini sağlamak amacıyla özel birBaseHTTPMiddleware ve asenkron bir HTTP istemcisi (httpx) kullanarak ProxyTracer'ı entegre ediyoruz.
Middleware
Bu uygulama, gerçek istemci IP'sini güvenli bir şekilde çıkarır, ProxyTracer'ı sorgulamak için asenkron bir bağlantı havuzu kullanır ve proxy bayrağı true dönerse kesin bir 403 Forbidden yanıtı verir.
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")
# Bağlantı havuzu (connection pooling) ve saf hız için kalıcı bir asenkron istemci başlatın
self.client = httpx.AsyncClient(timeout=0.5) # Kesin 500ms zaman aşımı
async def dispatch(self, request: Request, call_next):
# 1. Yük dengeleyicilerin/proxy'lerin arkasındaki gerçek IP'yi güvenli bir şekilde çıkarın
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
# Yerel geliştirme IP'lerini atlayın
if ip and ip not in ["127.0.0.1", "::1", "testclient"]:
try:
# 2. ProxyTracer API'sini asenkron olarak sorgulayın
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. Proxy tespit edilirse bağlantıyı derhal kesin
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: Ağ hatasını günlüğe kaydedin ve isteğin devam etmesine izin verin
print(f"ProxyTracer API timeout or failure: {e}")
# 4. Trafik temiz, rota işleyicisine devam edin
return await call_next(request)
# Middleware'i global olarak uygulayın
app.add_middleware(ProxyTracerMiddleware)Bağımlılık Notu: Bu uygulama asenkron HTTP istekleri için httpx kütüphanesini gerektirir. pip install httpx komutu ile yükleyin.
Son güncelleme tarihi