-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_forwarder.py
More file actions
150 lines (122 loc) · 4.22 KB
/
api_forwarder.py
File metadata and controls
150 lines (122 loc) · 4.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import asyncio
import json
from abc import ABC, abstractmethod
from functools import partial
import cloudscraper
import httpx
class BaseHttpClient(ABC):
@abstractmethod
async def request(self, method: str, url: str, **kwargs):
pass
class Forwarder:
def __init__(
self,
base_url: str,
backend: str = "cloudscraper",
client_options: dict | None = None,
*,
timeout = 10.0,
retries = 0,
retry_delay = 0.5,
):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.retries = retries
self.retry_delay = retry_delay
client_options = client_options or {}
if backend == "httpx":
self.client = HttpxClient(timeout=timeout, **client_options)
elif backend == "cloudscraper":
self.client = CloudscraperClient()
else:
raise ValueError(f"Unknown backend: {backend}")
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
close = getattr(self.client, "aclose", None)
if callable(close):
await close()
async def request(self, method: str, path: str, **kwargs):
url = self.base_url + path
last_exc = None
for attempt in range(self.retries + 1):
try:
return await asyncio.wait_for(
self.client.request(method, url, **kwargs),
timeout=self.timeout,
)
except Exception as e:
last_exc = e
if attempt < self.retries:
await asyncio.sleep(self.retry_delay)
else:
raise ForwarderError(
f"Request failed after {self.retries + 1} attempts"
) from e
async def get(self, path: str, **kwargs):
return await self.request("GET", path, **kwargs)
async def post(self, path: str, **kwargs):
return await self.request("POST", path, **kwargs)
class ForwarderResponse:
def __init__(self, *, status_code, headers, content, url=None):
self.status_code = status_code
self.headers = dict(headers)
self.content = content
self.url = url
@property
def text(self) -> str:
return self.content.decode(self._encoding(), errors="replace")
def json(self):
return json.loads(self.text)
def raise_for_status(self):
if self.status_code >= 400:
raise HTTPStatusError(
status_code=self.status_code,
text=self.text,
url=self.url,
)
return self
def _encoding(self) -> str:
ct = self.headers.get("content-type", "")
if "charset=" in ct:
return ct.split("charset=")[-1].split(";")[0]
return "utf-8"
class HttpxClient(BaseHttpClient):
def __init__(self, **opts):
self.client = httpx.AsyncClient(**opts)
async def request(self, method, url, **kwargs):
r = await self.client.request(method, url, **kwargs)
return ForwarderResponse(
status_code=r.status_code,
headers=r.headers,
content=r.content,
url=str(r.url),
)
async def aclose(self):
await self.client.aclose()
class CloudscraperClient(BaseHttpClient):
def __init__(self):
self.scraper = cloudscraper.create_scraper()
def _sync(self, method, url, **kwargs):
return self.scraper.request(method, url, **kwargs)
async def request(self, method, url, **kwargs):
loop = asyncio.get_running_loop()
r = await loop.run_in_executor(
None, partial(self._sync, method, url, **kwargs)
)
return ForwarderResponse(
status_code=r.status_code,
headers=r.headers,
content=r.content,
url=r.url,
)
async def aclose(self):
pass
class ForwarderError(Exception):
pass
class HTTPStatusError(ForwarderError):
def __init__(self, status_code: int, text: str, url: str | None = None):
self.status_code = status_code
self.text = text
self.url = url
super().__init__(f"HTTP {status_code} error for {url}")