Repository navigation
Expand file tree
/
Copy pathproxy_config.py
More file actions
476 lines (395 loc) · 17.4 KB
/
Copy pathproxy_config.py
File metadata and controls
476 lines (395 loc) · 17.4 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""Build proxy URLs from environment variables.
Two IPRoyal proxy types are supported:
- Residential (the default): one gateway, ``geo.iproyal.com``. IPRoyal reads
targeting and session options from the password, for example
``password_country-us_session-ab12cd34_lifetime-10m``. See
https://docs.iproyal.com/proxies/residential/proxy for the full syntax.
- Datacenter: you buy individual IPs, and the dashboard's Formatted Proxy List
gives each one its own host, port and credentials. Set
IPROYAL_DATACENTER_PROXIES to that list (comma-separated, or a path to a file
with one proxy per line). Rotating across the list happens in your code;
``DatacenterRotator`` below does round robin or random picks and drops IPs
that keep failing. See
https://docs.iproyal.com/proxies/datacenter/using-proxy-strings
Set PROXY_URL to use any other proxy instead; it overrides every IPROYAL_*
setting.
"""
from __future__ import annotations
import os
import random
import re
import secrets
import string
import threading
import time
from typing import Callable, Iterable, List, Mapping, Optional, Tuple, TypeVar, Union
from urllib.parse import quote, unquote, urlsplit
T = TypeVar("T")
DEFAULT_HOST = "geo.iproyal.com"
DEFAULT_HTTP_PORT = 12321
DEFAULT_SOCKS5_PORT = 32325
_SESSION_RE = re.compile(r"^[A-Za-z0-9]{8}$")
_LIFETIME_RE = re.compile(r"^(\d+)([smhd])$")
_UNIT_SECONDS = {"s": 1, "m": 60, "h": 3600, "d": 86400}
_MAX_LIFETIME_SECONDS = 7 * 86400
# Characters IPRoyal uses in the password suffix stay readable in the URL.
_SAFE_CHARS = "-_.~,"
class ProxyConfigError(ValueError):
"""Raised when the proxy settings are missing or invalid."""
def new_session_id() -> str:
"""Return a random 8-character alphanumeric session ID."""
alphabet = string.ascii_letters + string.digits
return "".join(secrets.choice(alphabet) for _ in range(8))
def _check_lifetime(lifetime: str) -> None:
match = _LIFETIME_RE.match(lifetime)
if not match:
raise ProxyConfigError(
f"lifetime {lifetime!r} must be a number and one unit: s, m, h or d (e.g. 10m)"
)
seconds = int(match.group(1)) * _UNIT_SECONDS[match.group(2)]
if not 1 <= seconds <= _MAX_LIFETIME_SECONDS:
raise ProxyConfigError(f"lifetime {lifetime!r} must be between 1s and 7d")
def build_password(
password: str,
*,
country: Optional[str] = None,
state: Optional[str] = None,
city: Optional[str] = None,
session: Optional[str] = None,
lifetime: Optional[str] = None,
) -> str:
"""Append IPRoyal targeting and session options to a password.
No session means a new IP with each request. A session keeps the same IP
for ``lifetime`` (default 10m when a session is set).
"""
parts = [password]
if country:
parts.append(f"country-{country.lower()}")
if state:
if not country or country.lower() != "us":
raise ProxyConfigError("state targeting needs country 'us'")
parts.append(f"state-{state.lower().replace(' ', '')}")
if city:
if not country:
raise ProxyConfigError("city targeting needs a country as well")
parts.append(f"city-{city.lower().replace(' ', '')}")
if lifetime and not session:
raise ProxyConfigError("lifetime only applies to a sticky session; set a session too")
if session:
if not _SESSION_RE.match(session):
raise ProxyConfigError("session must be exactly 8 letters or digits")
lifetime = lifetime or "10m"
_check_lifetime(lifetime)
parts.append(f"session-{session}")
parts.append(f"lifetime-{lifetime}")
return "_".join(parts)
def build_proxy_url(
username: str,
password: str,
*,
host: str = DEFAULT_HOST,
port: Optional[int] = None,
scheme: str = "http",
country: Optional[str] = None,
state: Optional[str] = None,
city: Optional[str] = None,
session: Optional[str] = None,
lifetime: Optional[str] = None,
) -> str:
"""Return a proxy URL such as http://user:pass_country-us@geo.iproyal.com:12321."""
if not username or not password:
raise ProxyConfigError("username and password are required")
if scheme not in ("http", "socks5"):
raise ProxyConfigError("scheme must be 'http' or 'socks5'")
if port is None:
port = DEFAULT_SOCKS5_PORT if scheme == "socks5" else DEFAULT_HTTP_PORT
full_password = build_password(
password, country=country, state=state, city=city, session=session, lifetime=lifetime
)
user = quote(username, safe=_SAFE_CHARS)
secret = quote(full_password, safe=_SAFE_CHARS)
return f"{scheme}://{user}:{secret}@{host}:{port}"
def _get(env: Mapping[str, str], key: str) -> Optional[str]:
value = env.get(key, "").strip()
return value or None
def proxy_url_from_env(env: Optional[Mapping[str, str]] = None, **overrides) -> str:
"""Build the proxy URL from environment variables.
PROXY_URL wins if it's set. Otherwise the IPROYAL_* variables are used.
Keyword overrides (country=..., session=...) replace the matching
environment value, which is handy in examples.
"""
env = os.environ if env is None else env
proxy_url = _get(env, "PROXY_URL")
if proxy_url:
return proxy_url
username = _get(env, "IPROYAL_USERNAME")
password = _get(env, "IPROYAL_PASSWORD")
if not username or not password:
raise ProxyConfigError(
"No proxy configured. Copy .env.example to .env and set IPROYAL_USERNAME "
"and IPROYAL_PASSWORD, or set PROXY_URL to use another proxy."
)
port = _get(env, "IPROYAL_PORT")
settings = {
"host": _get(env, "IPROYAL_HOST") or DEFAULT_HOST,
"port": int(port) if port else None,
"scheme": _get(env, "IPROYAL_SCHEME") or "http",
"country": _get(env, "IPROYAL_COUNTRY"),
"state": _get(env, "IPROYAL_STATE"),
"city": _get(env, "IPROYAL_CITY"),
"session": _get(env, "IPROYAL_SESSION"),
"lifetime": _get(env, "IPROYAL_LIFETIME"),
}
settings.update(overrides)
if not settings["session"]:
settings["lifetime"] = None
return build_proxy_url(username, password, **settings)
def load_dotenv_if_present() -> None:
"""Load a .env file from the current directory if python-dotenv is installed."""
try:
from dotenv import load_dotenv
except ImportError:
return
load_dotenv()
# --- Proxy URL helpers ---------------------------------------------------------
def split_proxy_url(proxy_url: str) -> Tuple[str, Optional[str], Optional[str]]:
"""Split ``scheme://user:pass@host:port`` into (server, username, password).
urllib3, Playwright and the Selenium relay take the credentials separately
from the proxy address. The username and password come back decoded, so
``pass_country-us`` stays exactly as IPRoyal expects it.
"""
parts = urlsplit(proxy_url)
try:
port = parts.port
except ValueError:
port = None
if not parts.scheme or not parts.hostname or not port:
raise ProxyConfigError(
f"proxy URL {redact(proxy_url)!r} needs a scheme, host and port, "
"e.g. http://user:pass@host:12321"
)
server = f"{parts.scheme}://{parts.hostname}:{port}"
username = unquote(parts.username) if parts.username is not None else None
password = unquote(parts.password) if parts.password is not None else None
return server, username, password
def redact(proxy_url: str) -> str:
"""Return the proxy URL with the password replaced by ***, for printing."""
parts = urlsplit(proxy_url)
if parts.password is None:
return proxy_url
host = parts.netloc.rpartition("@")[2]
return parts._replace(netloc=f"{parts.username}:***@{host}").geturl()
# --- Datacenter proxies: a list of IPs, rotated in your code --------------------
def _check_port(port: str, entry: str) -> None:
if not port.isdigit() or not 1 <= int(port) <= 65535:
raise ProxyConfigError(f"datacenter proxy {entry!r} has no valid port")
_ENTRY_HELP = "use host:port:user:pass, user:pass@host:port or a full proxy URL"
def parse_proxy_entry(entry: str, scheme: str = "http") -> str:
"""Turn one line of a proxy list into a proxy URL.
Accepted forms (the dashboard lets you pick the list format):
- ``http://user:pass@45.12.106.20:12323`` or ``socks5://...`` (kept as is)
- ``user:pass@45.12.106.20:12323``
- ``45.12.106.20:12323:user:pass`` (host, port, username, password)
- ``user:pass:45.12.106.20:12323`` (username, password, host, port)
- ``45.12.106.20:12323`` (no credentials: for a whitelisted IP)
"""
entry = entry.strip()
if not entry:
raise ProxyConfigError("empty proxy entry")
if "://" in entry:
split_proxy_url(entry) # checks the scheme, host and port
return entry
tail = entry.rpartition("@")[2]
if "@" in entry and re.fullmatch(r"[A-Za-z0-9.-]+:\d+", tail):
url = f"{scheme}://{entry}"
split_proxy_url(url)
return url
fields = entry.split(":")
if len(fields) == 2:
host, port = fields
_check_port(port, entry)
return f"{scheme}://{host}:{port}"
if len(fields) >= 4:
if "." in fields[0] and fields[1].isdigit():
host, port, username = fields[0], fields[1], fields[2]
password = ":".join(fields[3:])
elif "." in fields[-2] and fields[-1].isdigit():
username, host, port = fields[0], fields[-2], fields[-1]
password = ":".join(fields[1:-2])
else:
raise ProxyConfigError(f"can't read datacenter proxy {entry!r}: {_ENTRY_HELP}")
_check_port(port, entry)
user = quote(username, safe=_SAFE_CHARS)
secret = quote(password, safe=_SAFE_CHARS)
return f"{scheme}://{user}:{secret}@{host}:{port}"
raise ProxyConfigError(f"can't read datacenter proxy {entry!r}: {_ENTRY_HELP}")
def parse_datacenter_proxies(value: Union[str, Iterable[str]], scheme: str = "http") -> List[str]:
"""Parse a proxy list: comma- or newline-separated text, or a list of entries.
Blank lines and lines starting with # are skipped. Duplicates are dropped.
"""
if scheme not in ("http", "socks5"):
raise ProxyConfigError("scheme must be 'http' or 'socks5'")
if isinstance(value, str):
entries = []
for line in value.splitlines():
line = line.strip()
if line and not line.startswith("#"):
entries.extend(part for part in re.split(r"[,\s]+", line) if part)
else:
entries = [item.strip() for item in value if item.strip()]
proxies = [parse_proxy_entry(entry, scheme) for entry in entries]
return list(dict.fromkeys(proxies))
def datacenter_proxies_from_env(env: Optional[Mapping[str, str]] = None) -> List[str]:
"""Read IPROYAL_DATACENTER_PROXIES: a comma-separated list or a path to a file."""
env = os.environ if env is None else env
value = _get(env, "IPROYAL_DATACENTER_PROXIES")
if not value:
raise ProxyConfigError(
"No datacenter proxies configured. Set IPROYAL_DATACENTER_PROXIES to the "
"Formatted Proxy List from your dashboard (comma-separated) or to a file "
"with one proxy per line."
)
if os.path.isfile(value):
with open(value, encoding="utf-8") as handle:
value = handle.read()
scheme = _get(env, "IPROYAL_DATACENTER_SCHEME") or "http"
proxies = parse_datacenter_proxies(value, scheme=scheme)
if not proxies:
raise ProxyConfigError("IPROYAL_DATACENTER_PROXIES is set but lists no proxies")
return proxies
class GatewayProxy:
"""One proxy URL for every request.
With IPRoyal residential proxies the gateway picks the IP: a new one with
each request, or the same one for a sticky session. There's nothing to
rotate in code, so ``next()`` returns the same URL each time.
"""
def __init__(self, url: str) -> None:
self.url = url
@property
def active(self) -> List[str]:
return [self.url]
def next(self) -> str:
return self.url
def report_success(self, proxy: str) -> None:
pass
def report_failure(self, proxy: str) -> None:
pass
class DatacenterRotator:
"""Hand out datacenter proxies from a list, round robin or at random.
Call ``report_failure(proxy)`` when a request through that proxy fails
(connection error, 407, 403, 429 and so on) and ``report_success(proxy)``
when it works. A proxy that fails ``max_failures`` times in a row is
dropped from the rotation. Safe to share between threads.
"""
STRATEGIES = ("round_robin", "random")
def __init__(
self,
proxies: Iterable[str],
*,
strategy: str = "round_robin",
max_failures: int = 3,
rng: Optional[random.Random] = None,
) -> None:
self._proxies = list(dict.fromkeys(proxies))
if not self._proxies:
raise ProxyConfigError("the datacenter proxy list is empty")
if strategy not in self.STRATEGIES:
raise ProxyConfigError(f"strategy must be one of: {', '.join(self.STRATEGIES)}")
if max_failures < 1:
raise ProxyConfigError("max_failures must be 1 or more")
self.strategy = strategy
self.max_failures = max_failures
self._failures = {proxy: 0 for proxy in self._proxies}
self._dropped: List[str] = []
self._index = 0
self._rng = rng or random.Random()
self._lock = threading.Lock()
@property
def active(self) -> List[str]:
with self._lock:
return list(self._proxies)
@property
def dropped(self) -> List[str]:
with self._lock:
return list(self._dropped)
def next(self) -> str:
with self._lock:
if not self._proxies:
raise ProxyConfigError(
f"No datacenter proxies left: each one failed {self.max_failures} "
"times in a row. Check the list in your dashboard."
)
if self.strategy == "random":
return self._rng.choice(self._proxies)
proxy = self._proxies[self._index]
self._index = (self._index + 1) % len(self._proxies)
return proxy
def report_success(self, proxy: str) -> None:
with self._lock:
if proxy in self._failures:
self._failures[proxy] = 0
def report_failure(self, proxy: str) -> None:
with self._lock:
if proxy not in self._proxies:
return
self._failures[proxy] += 1
if self._failures[proxy] < self.max_failures:
return
position = self._proxies.index(proxy)
del self._proxies[position]
self._dropped.append(proxy)
if position < self._index:
self._index -= 1
self._index = self._index % len(self._proxies) if self._proxies else 0
ProxySource = Union[GatewayProxy, DatacenterRotator]
PROXY_TYPES = ("residential", "datacenter")
def proxy_source_from_env(
env: Optional[Mapping[str, str]] = None, proxy_type: Optional[str] = None, **overrides
) -> ProxySource:
"""Pick the proxy source the examples use.
- PROXY_URL set: that proxy for every request.
- proxy_type (or IPROYAL_PROXY_TYPE) "residential", the default: the
IPRoyal gateway built from the IPROYAL_* settings. Keyword overrides
(country=..., session=...) go to proxy_url_from_env.
- "datacenter": a DatacenterRotator over IPROYAL_DATACENTER_PROXIES, using
IPROYAL_DATACENTER_ROTATION (round_robin or random).
"""
env = os.environ if env is None else env
proxy_url = _get(env, "PROXY_URL")
if proxy_url:
return GatewayProxy(proxy_url)
proxy_type = (proxy_type or _get(env, "IPROYAL_PROXY_TYPE") or "residential").lower()
if proxy_type == "residential":
return GatewayProxy(proxy_url_from_env(env, **overrides))
if proxy_type == "datacenter":
strategy = _get(env, "IPROYAL_DATACENTER_ROTATION") or "round_robin"
return DatacenterRotator(datacenter_proxies_from_env(env), strategy=strategy)
raise ProxyConfigError(
f"proxy type must be one of: {', '.join(PROXY_TYPES)} (got {proxy_type!r})"
)
def describe(source: ProxySource) -> str:
"""A one-line description of a proxy source with passwords hidden."""
if isinstance(source, DatacenterRotator):
return f"{len(source.active)} datacenter proxies, {source.strategy.replace('_', ' ')}"
return redact(source.url)
def try_proxies(source: ProxySource, call: Callable[[str], T], *, attempts: int = 3, backoff: float = 1.0) -> T:
"""Run ``call(proxy_url)`` and move to the next proxy when it raises.
Each outcome is reported to the source, so a DatacenterRotator drops IPs
that keep failing. Between tries it waits ``backoff`` seconds times the
attempt number. After ``attempts`` tries the last error is raised.
"""
last_error: Optional[Exception] = None
for attempt in range(1, attempts + 1):
proxy = source.next()
try:
result = call(proxy)
except Exception as exc: # count any failure and try the next proxy
source.report_failure(proxy)
last_error = exc
if attempt < attempts and backoff:
time.sleep(backoff * attempt)
continue
source.report_success(proxy)
return result
assert last_error is not None
raise last_error