async aiohttp proxy - fixes event loop blocking
Browse filesFiles changed (2)
- Dockerfile+2-2
- app.py+42-25
123456FROM python:3.11-slimRUN pip install fastapi uvicorn --no-cache-dirCOPY app.py /app/app.pyWORKDIR /appEXPOSE 7860CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456FROM python:3.11-slimWORKDIR /appRUN pip install --no-cache-dir fastapi uvicorn aiohttpCOPY app.py .EXPOSE 7860CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
123456789101112131415162 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse, Responseimport json, time, os, sslimport urllib.request as ureq, urllib.errorapp = FastAPI()log = []_ctx = ssl.create_default_context()_ctx.check_hostname = False_ctx.verify_mode = ssl.CERT_NONE@app.get("/static.txt")def static_txt():return Response(content="line-one\nline-two\nline-three\n", media_type="text/plain")2 unmodified linesasync def capture_txt(request: Request):h = dict(request.headers)client_ip = request.client.host if request.client else "?"entry = {"t": round(time.time()), "type": "capture", "client": client_ip, "xff": h.get("x-forwarded-for",""), "all_headers": h}log.append(entry)lines = [f"client_ip: {client_ip}"]for k, v in h.items():lines.append(f"{k}: {v[:100]}")content = "\n".join(lines) + "\n"return Response(content=content, media_type="text/plain")@app.get("/miniproxy.txt")async def miniproxy(to: str = ""):"""Fetch URL, return only first 500 chars as compact text lines"""try:req = ureq.Request(to, headers={"User-Agent": "python-urllib/3.11", "Accept-Encoding": "identity"})r = ureq.urlopen(req, timeout=8, context=_ctx)raw = r.read(1024).decode(errors="replace")status = r.statuslog.append({"t": round(time.time()), "type": "miniproxy_ok", "to": to, "status": status, "preview": raw[:200]})# Return as multiple key:value lines (always < 571 bytes)lines = [f"status: {status}",f"url: {to[:100]}",f"data: {raw[:400].replace(chr(10), ' ').replace(chr(13), '')}",]content = "\n".join(lines) + "\n"except urllib.error.HTTPError as e:body = e.read(500).decode(errors="replace")log.append({"t": round(time.time()), "type": "miniproxy_err", "to": to, "code": e.code, "body": body[:200]})content = f"status: {e.code}\nurl: {to[:100]}\ndata: {body[:300].replace(chr(10),' ')}\n"except Exception as e:content = f"status: error\nurl: {to[:100]}\ndata: {str(e)[:200]}\n"log.append({"t": round(time.time()), "type": "miniproxy_exc", "to": to, "error": str(e)[:200]})return Response(content=content, media_type="text/plain")@app.post("/webhook")1234567891011122 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse, Responseimport json, time, os, ssl, asyncioimport aiohttpapp = FastAPI()log = []@app.get("/static.txt")def static_txt():return Response(content="line-one\nline-two\nline-three\n", media_type="text/plain")2 unmodified linesasync def capture_txt(request: Request):h = dict(request.headers)client_ip = request.client.host if request.client else "?"entry = {"t": round(time.time()), "type": "capture", "client": client_ip,"xff": h.get("x-forwarded-for",""), "all_headers": h}log.append(entry)lines = [f"client_ip: {client_ip}", f"xff: {h.get('x-forwarded-for','')}"]for k, v in h.items():lines.append(f"{k}: {v[:200]}")content = "\n".join(lines) + "\n"return Response(content=content, media_type="text/plain")@app.get("/miniproxy.txt")async def miniproxy(request: Request, to: str = ""):"""Async proxy - fetch URL with aiohttp, return compact key:value lines"""caller_hdrs = dict(request.headers)log_entry = {"t": round(time.time()), "type": "miniproxy_start", "to": to}try:ssl_ctx = ssl.create_default_context()ssl_ctx.check_hostname = Falsessl_ctx.verify_mode = ssl.CERT_NONEasync with aiohttp.ClientSession() as session:async with session.get(to,ssl=ssl_ctx,timeout=aiohttp.ClientTimeout(total=8),headers={"User-Agent": "python-aiohttp/3.x", "Accept-Encoding": "identity"}) as resp:raw = await resp.text(errors="replace")status = resp.statusresp_hdrs = dict(resp.headers)log_entry.update({"type": "miniproxy_ok", "status": status, "len": len(raw), "preview": raw[:200]})log.append(log_entry)# Return as compact key:value lines, strip all newlines from dataclean_data = raw[:500].replace("\n", " ").replace("\r", "")lines = [f"status: {status}",f"url: {to[:150]}",f"data: {clean_data}",]content = "\n".join(lines) + "\n"except aiohttp.ClientResponseError as e:log_entry.update({"type": "miniproxy_http_err", "code": e.status, "msg": str(e)[:200]})log.append(log_entry)content = f"status: {e.status}\nurl: {to[:150]}\ndata: {str(e.message)[:300]}\n"except Exception as e:log_entry.update({"type": "miniproxy_err", "error": str(e)[:200]})log.append(log_entry)content = f"status: error\nurl: {to[:150]}\ndata: {str(e)[:300]}\n"return Response(content=content, media_type="text/plain")@app.post("/webhook")
Dockerfile+2-2
app.py+42-25