Spaces:
Runtime error
Runtime error
Create integrations/http.py
Browse files- bot/integrations/http.py +25 -0
bot/integrations/http.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PATH: bot/integrations/http.py
|
| 2 |
+
import httpx
|
| 3 |
+
from bot.core.settings import HTTP_TIMEOUT_SEC, MAX_RETRIES
|
| 4 |
+
|
| 5 |
+
_async_client: httpx.AsyncClient | None = None
|
| 6 |
+
|
| 7 |
+
def get_client() -> httpx.AsyncClient:
|
| 8 |
+
global _async_client
|
| 9 |
+
if _async_client is None:
|
| 10 |
+
_async_client = httpx.AsyncClient(timeout=HTTP_TIMEOUT_SEC, follow_redirects=True)
|
| 11 |
+
return _async_client
|
| 12 |
+
|
| 13 |
+
async def post_json(url: str, headers: dict, payload: dict) -> dict:
|
| 14 |
+
c = get_client()
|
| 15 |
+
last_err = None
|
| 16 |
+
for _ in range(MAX_RETRIES + 1):
|
| 17 |
+
try:
|
| 18 |
+
r = await c.post(url, headers=headers, json=payload)
|
| 19 |
+
data = r.json() if r.headers.get("content-type","").startswith("application/json") else {}
|
| 20 |
+
if r.status_code >= 400:
|
| 21 |
+
return {"ok": False, "status": r.status_code, "data": data, "text": r.text[:300]}
|
| 22 |
+
return data
|
| 23 |
+
except Exception as e:
|
| 24 |
+
last_err = e
|
| 25 |
+
return {"ok": False, "status": 0, "err": str(last_err)}
|