memorylake-proxy 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Send an HTTP request through an HTTP proxy, with the standard library only.
|
|
2
|
+
|
|
3
|
+
from memorylake_proxy import fetch
|
|
4
|
+
|
|
5
|
+
response = fetch("https://example.com/", proxy="http://127.0.0.1:3128")
|
|
6
|
+
|
|
7
|
+
An ``http://`` URL is sent to the proxy as an absolute-form request; an
|
|
8
|
+
``https://`` URL goes through a ``CONNECT`` tunnel. See ``fetch``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import http.client
|
|
15
|
+
import ssl
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Mapping, Optional, Sequence, Tuple
|
|
18
|
+
from urllib.parse import urlsplit
|
|
19
|
+
|
|
20
|
+
__all__ = ["ProxyError", "Response", "fetch"]
|
|
21
|
+
__version__ = "0.0.1"
|
|
22
|
+
|
|
23
|
+
_DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProxyError(Exception):
|
|
27
|
+
"""The proxy refused to open a tunnel.
|
|
28
|
+
|
|
29
|
+
``status`` is the status code it answered the ``CONNECT`` with, when one
|
|
30
|
+
could be read.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str, status: Optional[int] = None) -> None:
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.status = status
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Response:
|
|
40
|
+
"""What the server answered."""
|
|
41
|
+
|
|
42
|
+
status: int
|
|
43
|
+
reason: str
|
|
44
|
+
headers: Sequence[Tuple[str, str]] = field(repr=False)
|
|
45
|
+
body: bytes = field(repr=False)
|
|
46
|
+
|
|
47
|
+
def header(self, name: str) -> Optional[str]:
|
|
48
|
+
"""The first value of a header, matched without regard to case, or None."""
|
|
49
|
+
wanted = name.lower()
|
|
50
|
+
for key, value in self.headers:
|
|
51
|
+
if key.lower() == wanted:
|
|
52
|
+
return value
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _parse_proxy(proxy: str) -> Tuple[str, int]:
|
|
57
|
+
parts = urlsplit(proxy)
|
|
58
|
+
try:
|
|
59
|
+
port = parts.port
|
|
60
|
+
except ValueError:
|
|
61
|
+
port = None
|
|
62
|
+
if (
|
|
63
|
+
parts.scheme != "http"
|
|
64
|
+
or not parts.hostname
|
|
65
|
+
or port is None
|
|
66
|
+
or parts.username is not None
|
|
67
|
+
or parts.path not in ("", "/")
|
|
68
|
+
or parts.query
|
|
69
|
+
or parts.fragment
|
|
70
|
+
):
|
|
71
|
+
raise ValueError("proxy must be http://<host>:<port>; give credentials with proxy_auth")
|
|
72
|
+
return parts.hostname, port
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _parse_url(url: str) -> Tuple[str, str, int, str]:
|
|
76
|
+
parts = urlsplit(url)
|
|
77
|
+
if parts.scheme not in _DEFAULT_PORTS or not parts.hostname:
|
|
78
|
+
raise ValueError("url must be an http:// or https:// URL with a host")
|
|
79
|
+
if parts.username is not None:
|
|
80
|
+
raise ValueError("url must not carry credentials")
|
|
81
|
+
port = parts.port or _DEFAULT_PORTS[parts.scheme]
|
|
82
|
+
target = parts.path or "/"
|
|
83
|
+
if parts.query:
|
|
84
|
+
target += "?" + parts.query
|
|
85
|
+
return parts.scheme, parts.hostname, port, target
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _basic(credentials: Tuple[str, str]) -> str:
|
|
89
|
+
user, password = credentials
|
|
90
|
+
return "Basic " + base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def fetch(
|
|
94
|
+
url: str,
|
|
95
|
+
*,
|
|
96
|
+
proxy: str,
|
|
97
|
+
method: str = "GET",
|
|
98
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
99
|
+
body: Optional[bytes] = None,
|
|
100
|
+
proxy_auth: Optional[Tuple[str, str]] = None,
|
|
101
|
+
timeout: float = 30.0,
|
|
102
|
+
tunnel: Optional[bool] = None,
|
|
103
|
+
ssl_context: Optional[ssl.SSLContext] = None,
|
|
104
|
+
) -> Response:
|
|
105
|
+
"""Send one request to ``url`` through the HTTP proxy at ``proxy``.
|
|
106
|
+
|
|
107
|
+
``tunnel`` decides how: ``None`` tunnels an ``https://`` URL and sends an
|
|
108
|
+
``http://`` one in absolute form; ``True`` tunnels either. ``https://``
|
|
109
|
+
cannot be sent without a tunnel. ``proxy_auth`` is a (user, password) pair
|
|
110
|
+
for the proxy's Basic authentication; through a tunnel it goes on the
|
|
111
|
+
``CONNECT``. Each call opens its own connection and closes it before
|
|
112
|
+
returning.
|
|
113
|
+
"""
|
|
114
|
+
proxy_host, proxy_port = _parse_proxy(proxy)
|
|
115
|
+
scheme, host, port, target = _parse_url(url)
|
|
116
|
+
if tunnel is None:
|
|
117
|
+
tunnel = scheme == "https"
|
|
118
|
+
if scheme == "https" and not tunnel:
|
|
119
|
+
raise ValueError("an https:// URL is sent through a tunnel")
|
|
120
|
+
|
|
121
|
+
request_headers = dict(headers or {})
|
|
122
|
+
proxy_headers = {"Proxy-Authorization": _basic(proxy_auth)} if proxy_auth else {}
|
|
123
|
+
|
|
124
|
+
connection: http.client.HTTPConnection
|
|
125
|
+
if scheme == "https":
|
|
126
|
+
context = ssl_context if ssl_context is not None else ssl.create_default_context()
|
|
127
|
+
connection = http.client.HTTPSConnection(proxy_host, proxy_port, timeout=timeout, context=context)
|
|
128
|
+
else:
|
|
129
|
+
connection = http.client.HTTPConnection(proxy_host, proxy_port, timeout=timeout)
|
|
130
|
+
try:
|
|
131
|
+
if tunnel:
|
|
132
|
+
connection.set_tunnel(host, port, headers=proxy_headers)
|
|
133
|
+
try:
|
|
134
|
+
connection.connect()
|
|
135
|
+
except OSError as error:
|
|
136
|
+
message = str(error)
|
|
137
|
+
if message.startswith("Tunnel connection failed"):
|
|
138
|
+
status = _status_of(message)
|
|
139
|
+
raise ProxyError(f"the proxy refused the tunnel to {host}:{port}: {message}", status) from None
|
|
140
|
+
raise
|
|
141
|
+
connection.request(method, target, body=body, headers=request_headers)
|
|
142
|
+
else:
|
|
143
|
+
authority = f"[{host}]" if ":" in host else host
|
|
144
|
+
if port != _DEFAULT_PORTS["http"]:
|
|
145
|
+
authority += f":{port}"
|
|
146
|
+
absolute = f"http://{authority}{target}"
|
|
147
|
+
connection.request(method, absolute, body=body, headers={**request_headers, **proxy_headers})
|
|
148
|
+
answer = connection.getresponse()
|
|
149
|
+
return Response(
|
|
150
|
+
status=answer.status,
|
|
151
|
+
reason=answer.reason,
|
|
152
|
+
headers=tuple(answer.getheaders()),
|
|
153
|
+
body=answer.read(),
|
|
154
|
+
)
|
|
155
|
+
finally:
|
|
156
|
+
connection.close()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _status_of(message: str) -> Optional[int]:
|
|
160
|
+
"""The status in http.client's "Tunnel connection failed: 407 ..." message."""
|
|
161
|
+
words = message.split(":", 1)[-1].split()
|
|
162
|
+
return int(words[0]) if words and words[0].isdigit() else None
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: memorylake-proxy
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Send HTTP requests through an HTTP proxy, with the Python standard library only.
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
10
|
+
Import-Name: memorylake_proxy
|
|
11
|
+
|
|
12
|
+
# memorylake-proxy
|
|
13
|
+
|
|
14
|
+
A small Python client that sends an HTTP request through an HTTP proxy. It uses
|
|
15
|
+
the standard library only.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from memorylake_proxy import fetch
|
|
19
|
+
|
|
20
|
+
response = fetch("https://example.com/", proxy="http://127.0.0.1:3128")
|
|
21
|
+
print(response.status, response.header("content-type"), len(response.body))
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`fetch(url, *, proxy, ...)` sends one request and returns a `Response` with
|
|
25
|
+
`status`, `reason`, `headers` and `body`.
|
|
26
|
+
|
|
27
|
+
- `proxy` is the proxy's address, `http://<host>:<port>`.
|
|
28
|
+
- An `http://` URL is sent to the proxy as an absolute-form request. An
|
|
29
|
+
`https://` URL goes through a `CONNECT` tunnel, and the server's certificate
|
|
30
|
+
is verified as usual. `tunnel=True` sends an `http://` URL through a tunnel
|
|
31
|
+
as well.
|
|
32
|
+
- `proxy_auth=("user", "password")` authenticates to the proxy with Basic
|
|
33
|
+
`Proxy-Authorization`.
|
|
34
|
+
- `method`, `headers`, `body` and `timeout` (in seconds, default 30) are the
|
|
35
|
+
request's own. `ssl_context` replaces the default TLS context for an `https://`
|
|
36
|
+
URL.
|
|
37
|
+
- A proxy that refuses the tunnel raises `ProxyError`, with the status it
|
|
38
|
+
answered. A proxy address that is not `http://<host>:<port>` raises
|
|
39
|
+
`ValueError`.
|
|
40
|
+
|
|
41
|
+
Requires Python 3.9 or later. No dependencies.
|
|
42
|
+
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
memorylake_proxy/__init__.py,sha256=V28EC1-SBSt5MAjzNbzPvEs_3MmJdZ23CUPq-ROrkSs,5653
|
|
2
|
+
memorylake_proxy-0.0.1.dist-info/WHEEL,sha256=rLJE8OLPBZbz7tqxs1yD-wA-ADa1Ec5PuYU-Y_PNWDI,81
|
|
3
|
+
memorylake_proxy-0.0.1.dist-info/METADATA,sha256=7DbXnIQ_cz5s_hg12bC6sobLQtB1h42BbXnWsa8_HCk,1596
|
|
4
|
+
memorylake_proxy-0.0.1.dist-info/RECORD,,
|