-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproxy_settings.py
More file actions
81 lines (72 loc) · 2.51 KB
/
proxy_settings.py
File metadata and controls
81 lines (72 loc) · 2.51 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
from typing import Dict, Optional
from urllib.parse import quote
class ProxySettings:
"""
A simple data model for configuring HTTP(S) proxy settings.
"""
HTTP_SCHEME: str = "http://"
HTTPS_SCHEME: str = "https://"
address: str
port: Optional[int]
username: Optional[str]
password: Optional[str]
def __init__(self, address: str, port: Optional[int] = None,
username: Optional[str] = None, password: Optional[str] = None) -> None:
"""
Parameters
----------
address : str
Hostname or IP of the proxy.
port : int, optional
Port of the proxy server.
username : str, optional
Username for authentication.
password : str, optional
Password for authentication.
"""
self.address = address
self.port = port
self.username = username
self.password = password
def __repr__(self) -> str:
"""
Developer-friendly representation.
"""
return (
f"ProxySettings(address={self.address!r}, "
f"port={self.port!r}, "
f"username={self.username!r}, "
f"password={'***' if self.password else None})"
)
def __str__(self) -> str:
"""
Human-friendly string for display/logging.
"""
user_info = f"{self.username}:***@" if self.username else ""
port = f":{self.port}" if self.port else ""
return f"{user_info}{self.address}{port}"
def _sanitize_address(self) -> str:
addr = (self.address or "").strip()
# Trim scheme if present
if addr.startswith(self.HTTP_SCHEME):
addr = addr[len(self.HTTP_SCHEME):]
elif addr.startswith(self.HTTPS_SCHEME):
addr = addr[len(self.HTTPS_SCHEME):]
# Drop trailing slash if user typed a URL-like form
return addr.rstrip("/")
def to_proxies(self) -> Dict[str, str]:
"""
Build a `requests`-compatible proxies dictionary.
"""
host = self._sanitize_address()
auth = ""
if self.username is not None:
# URL-encode in case of special chars
u = quote(self.username, safe="")
p = quote(self.password or "", safe="")
auth = f"{u}:{p}@"
port = f":{self.port}" if self.port is not None else ""
return {
"http": f"{self.HTTP_SCHEME}{auth}{host}{port}",
"https": f"{self.HTTPS_SCHEME}{auth}{host}{port}",
}