FastAPI (Python)
صُمم FastAPI لتطبيقات الويب غير المتزامنة عالية الأداء. للحفاظ على تلك السرعة، ندمج ProxyTracer باستخدامBaseHTTPMiddleware مخصص وعميل HTTP غير متزامن (httpx) لضمان عدم حظر حلقة الأحداث مطلقاً.
البرمجية الوسيطة
يستخرج هذا التطبيق عنوان IP الحقيقي للعميل بأمان، ويستخدم مجمع اتصالات غير متزامن للاستعلام من ProxyTracer، ويرجع رمز 403 Forbidden صارماً إذا أرجعت علامة proxy القيمة true.
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")
# تهيئة عميل غير متزامن دائم لتجميع الاتصالات وتحقيق سرعة قصوى
self.client = httpx.AsyncClient(timeout=0.5) # مهلة صارمة 500 مللي ثانية
async def dispatch(self, request: Request, call_next):
# 1. استخراج عنوان IP الحقيقي بأمان خلف موازنات الحمل/البروكسيات
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
# تخطي عناوين IP للتطوير المحلي
if ip and ip not in ["127.0.0.1", "::1", "testclient"]:
try:
# 2. الاستعلام من ProxyTracer API بشكل غير متزامن
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. قطع الاتصال فوراً إذا تم اكتشاف بروكسي
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: تسجيل خطأ الشبكة والسماح للطلب بالمتابعة
print(f"ProxyTracer API timeout or failure: {e}")
# 4. حركة المرور نظيفة، المتابعة إلى معالج المسار
return await call_next(request)
# تطبيق البرمجية الوسيطة عالمياً
app.add_middleware(ProxyTracerMiddleware)ملاحظة التبعية: يتطلب هذا التطبيق مكتبة httpx لطلبات HTTP غير المتزامنة. قم بتثبيتها عبر pip install httpx.
آخر تحديث في