tls-client-python 1.16.0.1__py3-none-macosx_10_9_universal2.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.
- tls_client/__init__.py +81 -0
- tls_client/_client_hints.py +162 -0
- tls_client/_core.py +4738 -0
- tls_client/_default_headers.py +370 -0
- tls_client/_multipart_boundary.py +54 -0
- tls_client/adapters.py +8 -0
- tls_client/auth.py +45 -0
- tls_client/bin/tls-client-darwin-amd64.dylib +0 -0
- tls_client/bin/tls-client-darwin-arm64.dylib +0 -0
- tls_client/context.py +347 -0
- tls_client/cookies.py +189 -0
- tls_client/ech.py +50 -0
- tls_client/exceptions.py +91 -0
- tls_client/hooks.py +30 -0
- tls_client/models.py +6 -0
- tls_client/requests_compat.py +674 -0
- tls_client/status_codes.py +45 -0
- tls_client/structures.py +60 -0
- tls_client_python-1.16.0.1.dist-info/METADATA +620 -0
- tls_client_python-1.16.0.1.dist-info/RECORD +23 -0
- tls_client_python-1.16.0.1.dist-info/WHEEL +5 -0
- tls_client_python-1.16.0.1.dist-info/licenses/LICENSE +27 -0
- tls_client_python-1.16.0.1.dist-info/top_level.txt +1 -0
tls_client/models.py
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
"""Dependency-free Requests-compatible API over the native tls-client engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import absolute_import
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import inspect
|
|
7
|
+
import json as jsonlib
|
|
8
|
+
import math
|
|
9
|
+
import time
|
|
10
|
+
from datetime import timedelta
|
|
11
|
+
from http.client import responses as reason_phrases
|
|
12
|
+
from urllib.parse import urlencode, urljoin, urlsplit, urlunsplit
|
|
13
|
+
from urllib.request import getproxies
|
|
14
|
+
|
|
15
|
+
from tls_client import exceptions
|
|
16
|
+
from tls_client import _multipart_boundary
|
|
17
|
+
from tls_client.auth import HTTPBasicAuth
|
|
18
|
+
from tls_client.cookies import RequestsCookieJar, cookie_header, extract_cookies, merge_cookies
|
|
19
|
+
from tls_client.hooks import default_hooks, dispatch_hook, merge_hooks
|
|
20
|
+
from tls_client.structures import CaseInsensitiveDict
|
|
21
|
+
from tls_client._core import Session as NativeSession, SUPPORTED_CLIENT_IDENTIFIERS
|
|
22
|
+
from tls_client._core import _load_client_certificates, _resolve_proxy_url
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
REDIRECT_STATI = (301, 302, 303, 307, 308)
|
|
26
|
+
|
|
27
|
+
_REQUESTS_ATTRIBUTES = {
|
|
28
|
+
"adapters", "auth", "cert", "cookies", "headers", "hooks",
|
|
29
|
+
"max_redirects", "params", "proxies", "stream", "trust_env", "verify",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
_TLS_REQUEST_OPTIONS = {
|
|
33
|
+
"allow_empty_cookies", "catch_panics", "certificate_pinning_hosts",
|
|
34
|
+
"client_certificates", "client_identifier", "connect_headers",
|
|
35
|
+
"custom_tls_client", "default_headers", "disable_compression",
|
|
36
|
+
"disable_http3", "disable_ipv4", "disable_ipv6", "disable_keep_alives",
|
|
37
|
+
"force_http1", "h3_pseudo_header_order", "header_order",
|
|
38
|
+
"idle_conn_timeout_seconds", "local_address", "max_connections_per_host",
|
|
39
|
+
"max_idle_connections", "max_idle_connections_per_host",
|
|
40
|
+
"max_response_header_bytes", "pseudo_header_order",
|
|
41
|
+
"random_tls_extension_order", "read_buffer_size", "request_cookies",
|
|
42
|
+
"request_host_override", "server_name_overwrite", "tcp_mss", "tcp_ttl",
|
|
43
|
+
"tcp_window_scale", "tcp_window_size", "timeout_milliseconds", "with_debug",
|
|
44
|
+
"with_default_bad_pin_handler", "with_protocol_racing", "without_cookie_jar",
|
|
45
|
+
"write_buffer_size",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# Keep this list in sync with the native Session signature so both the
|
|
49
|
+
# requests-compatible facade and direct TLS users can discover every control.
|
|
50
|
+
_TLS_SESSION_OPTIONS = set(name for name in inspect.signature(NativeSession).parameters)
|
|
51
|
+
_TLS_REQUEST_OPTIONS.update(_TLS_SESSION_OPTIONS)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _merge_url_params(url, params):
|
|
55
|
+
if not params:
|
|
56
|
+
return url
|
|
57
|
+
query = urlencode(params, doseq=True)
|
|
58
|
+
scheme, netloc, path, old_query, fragment = urlsplit(url)
|
|
59
|
+
query = "&".join(filter(None, (old_query, query)))
|
|
60
|
+
return urlunsplit((scheme, netloc, path, query, fragment))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _body_bytes(value):
|
|
64
|
+
if value is None or isinstance(value, bytes):
|
|
65
|
+
return value
|
|
66
|
+
if isinstance(value, bytearray):
|
|
67
|
+
return bytes(value)
|
|
68
|
+
if isinstance(value, str):
|
|
69
|
+
return value.encode("utf-8")
|
|
70
|
+
if hasattr(value, "read"):
|
|
71
|
+
value = value.read()
|
|
72
|
+
return value.encode("utf-8") if isinstance(value, str) else bytes(value)
|
|
73
|
+
return b"".join(
|
|
74
|
+
chunk.encode("utf-8") if isinstance(chunk, str) else bytes(chunk)
|
|
75
|
+
for chunk in value
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _multipart(data, files, browser="chrome"):
|
|
80
|
+
boundary = _multipart_boundary.boundary(browser)
|
|
81
|
+
chunks = []
|
|
82
|
+
|
|
83
|
+
def add(value):
|
|
84
|
+
chunks.append(value.encode("utf-8") if isinstance(value, str) else value)
|
|
85
|
+
|
|
86
|
+
fields = data.items() if hasattr(data, "items") else (data or [])
|
|
87
|
+
for name, value in fields:
|
|
88
|
+
values = value if isinstance(value, (list, tuple)) else [value]
|
|
89
|
+
for item in values:
|
|
90
|
+
add("--%s\r\n" % boundary)
|
|
91
|
+
add('Content-Disposition: form-data; name="%s"\r\n\r\n' % name)
|
|
92
|
+
add(str(item))
|
|
93
|
+
add("\r\n")
|
|
94
|
+
|
|
95
|
+
entries = files.items() if hasattr(files, "items") else files
|
|
96
|
+
for name, value in entries:
|
|
97
|
+
filename, content_type, extra_headers, content = name, "application/octet-stream", {}, value
|
|
98
|
+
if isinstance(value, tuple):
|
|
99
|
+
filename, content = value[:2]
|
|
100
|
+
if len(value) > 2:
|
|
101
|
+
content_type = value[2]
|
|
102
|
+
if len(value) > 3:
|
|
103
|
+
extra_headers = value[3]
|
|
104
|
+
add("--%s\r\n" % boundary)
|
|
105
|
+
add('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (name, filename))
|
|
106
|
+
add("Content-Type: %s\r\n" % content_type)
|
|
107
|
+
for header, header_value in extra_headers.items():
|
|
108
|
+
add("%s: %s\r\n" % (header, header_value))
|
|
109
|
+
add("\r\n")
|
|
110
|
+
add(_body_bytes(content))
|
|
111
|
+
add("\r\n")
|
|
112
|
+
add("--%s--\r\n" % boundary)
|
|
113
|
+
return b"".join(chunks), "multipart/form-data; boundary=%s" % boundary
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _timeout_options(timeout):
|
|
117
|
+
if timeout is None:
|
|
118
|
+
return {}
|
|
119
|
+
if isinstance(timeout, (tuple, list)):
|
|
120
|
+
if len(timeout) != 2:
|
|
121
|
+
raise ValueError("timeout must be a number or a (connect, read) tuple")
|
|
122
|
+
values = [value for value in timeout if value is not None]
|
|
123
|
+
if not values:
|
|
124
|
+
return {}
|
|
125
|
+
timeout = max(values)
|
|
126
|
+
seconds = float(timeout)
|
|
127
|
+
if seconds <= 0:
|
|
128
|
+
raise ValueError("timeout must be greater than zero")
|
|
129
|
+
if seconds.is_integer():
|
|
130
|
+
return {"timeout": int(seconds)}
|
|
131
|
+
return {"timeout_milliseconds": max(1, int(math.ceil(seconds * 1000)))}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _transport_error(error, request):
|
|
135
|
+
message = str(error)
|
|
136
|
+
lowered = message.lower()
|
|
137
|
+
if "timeout" in lowered or "deadline exceeded" in lowered:
|
|
138
|
+
kind = exceptions.Timeout
|
|
139
|
+
elif "proxy" in lowered:
|
|
140
|
+
kind = exceptions.ProxyError
|
|
141
|
+
elif "certificate" in lowered or "tls" in lowered or "ssl" in lowered:
|
|
142
|
+
kind = exceptions.SSLError
|
|
143
|
+
else:
|
|
144
|
+
kind = exceptions.ConnectionError
|
|
145
|
+
return kind(message, request=request)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class Request(object):
|
|
149
|
+
def __init__(self, method=None, url=None, headers=None, files=None, data=None,
|
|
150
|
+
params=None, auth=None, cookies=None, hooks=None, json=None):
|
|
151
|
+
self.hooks = merge_hooks(hooks, None) if hooks else default_hooks()
|
|
152
|
+
self.method, self.url, self.headers = method, url, headers
|
|
153
|
+
self.files, self.data, self.json = files, data, json
|
|
154
|
+
self.params, self.auth, self.cookies = params, auth, cookies
|
|
155
|
+
|
|
156
|
+
def prepare(self):
|
|
157
|
+
prepared = PreparedRequest()
|
|
158
|
+
return prepared.prepare(
|
|
159
|
+
method=self.method, url=self.url, headers=self.headers, files=self.files,
|
|
160
|
+
data=self.data, params=self.params, auth=self.auth, cookies=self.cookies,
|
|
161
|
+
hooks=self.hooks, json=self.json,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class PreparedRequest(object):
|
|
166
|
+
def __init__(self):
|
|
167
|
+
self.method = self.url = self.body = None
|
|
168
|
+
self.headers = CaseInsensitiveDict()
|
|
169
|
+
self.hooks = default_hooks()
|
|
170
|
+
self._cookies = RequestsCookieJar()
|
|
171
|
+
|
|
172
|
+
def prepare(self, method=None, url=None, headers=None, files=None, data=None,
|
|
173
|
+
params=None, auth=None, cookies=None, hooks=None, json=None):
|
|
174
|
+
if not url:
|
|
175
|
+
raise exceptions.URLRequired("Invalid URL: no URL supplied")
|
|
176
|
+
parsed = urlsplit(str(url))
|
|
177
|
+
if not parsed.scheme:
|
|
178
|
+
raise exceptions.MissingSchema("Invalid URL %r: no scheme supplied" % url)
|
|
179
|
+
if parsed.scheme not in ("http", "https"):
|
|
180
|
+
raise exceptions.InvalidSchema("No connection adapter for %r" % url)
|
|
181
|
+
self.method = str(method or "GET").upper()
|
|
182
|
+
self.url = _merge_url_params(str(url), params)
|
|
183
|
+
self.headers = CaseInsensitiveDict(headers or {})
|
|
184
|
+
self.hooks = hooks or default_hooks()
|
|
185
|
+
|
|
186
|
+
if files:
|
|
187
|
+
self.body, content_type = _multipart(data, files)
|
|
188
|
+
self.headers.setdefault("Content-Type", content_type)
|
|
189
|
+
elif json is not None:
|
|
190
|
+
self.body = jsonlib.dumps(json, allow_nan=False).encode("utf-8")
|
|
191
|
+
self.headers.setdefault("Content-Type", "application/json")
|
|
192
|
+
elif hasattr(data, "items") or (
|
|
193
|
+
isinstance(data, (list, tuple)) and data and isinstance(data[0], tuple)
|
|
194
|
+
):
|
|
195
|
+
self.body = urlencode(data, doseq=True).encode("utf-8")
|
|
196
|
+
self.headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
|
|
197
|
+
else:
|
|
198
|
+
self.body = _body_bytes(data)
|
|
199
|
+
if self.body is not None:
|
|
200
|
+
self.headers["Content-Length"] = str(len(self.body))
|
|
201
|
+
|
|
202
|
+
self.prepare_cookies(cookies)
|
|
203
|
+
if auth is not None:
|
|
204
|
+
auth = HTTPBasicAuth(*auth) if isinstance(auth, tuple) else auth
|
|
205
|
+
if callable(auth):
|
|
206
|
+
auth(self)
|
|
207
|
+
return self
|
|
208
|
+
|
|
209
|
+
def prepare_cookies(self, cookies):
|
|
210
|
+
if cookies:
|
|
211
|
+
if isinstance(cookies, RequestsCookieJar):
|
|
212
|
+
self._cookies = cookies.copy()
|
|
213
|
+
else:
|
|
214
|
+
self._cookies.update(cookies)
|
|
215
|
+
value = cookie_header(self._cookies, self.url)
|
|
216
|
+
if value:
|
|
217
|
+
self.headers["Cookie"] = value
|
|
218
|
+
|
|
219
|
+
def copy(self):
|
|
220
|
+
copied = PreparedRequest()
|
|
221
|
+
copied.method, copied.url, copied.body = self.method, self.url, self.body
|
|
222
|
+
copied.headers = self.headers.copy()
|
|
223
|
+
copied.hooks = dict((key, list(value)) for key, value in self.hooks.items())
|
|
224
|
+
copied._cookies = self._cookies.copy()
|
|
225
|
+
return copied
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class Response(object):
|
|
229
|
+
def __init__(self):
|
|
230
|
+
self._content = b""
|
|
231
|
+
self.status_code = None
|
|
232
|
+
self.headers = CaseInsensitiveDict()
|
|
233
|
+
self.raw = self.url = self.encoding = self.reason = None
|
|
234
|
+
self.history = []
|
|
235
|
+
self.cookies = RequestsCookieJar()
|
|
236
|
+
self.elapsed = timedelta(0)
|
|
237
|
+
self.request = self.connection = self.used_protocol = self._next = None
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def content(self):
|
|
241
|
+
return self._content
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def text(self):
|
|
245
|
+
if not self._content:
|
|
246
|
+
return ""
|
|
247
|
+
try:
|
|
248
|
+
return self._content.decode(self.encoding or "utf-8", errors="replace")
|
|
249
|
+
except LookupError:
|
|
250
|
+
return self._content.decode("utf-8", errors="replace")
|
|
251
|
+
|
|
252
|
+
@property
|
|
253
|
+
def apparent_encoding(self):
|
|
254
|
+
try:
|
|
255
|
+
self._content.decode("utf-8")
|
|
256
|
+
return "utf-8"
|
|
257
|
+
except UnicodeDecodeError:
|
|
258
|
+
return "ISO-8859-1"
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def ok(self):
|
|
262
|
+
return self.status_code is not None and self.status_code < 400
|
|
263
|
+
|
|
264
|
+
@property
|
|
265
|
+
def is_redirect(self):
|
|
266
|
+
return "location" in self.headers and self.status_code in REDIRECT_STATI
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def is_permanent_redirect(self):
|
|
270
|
+
return "location" in self.headers and self.status_code in (301, 308)
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def next(self):
|
|
274
|
+
return self._next
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def links(self):
|
|
278
|
+
result = {}
|
|
279
|
+
for value in self.headers.get("link", "").split(","):
|
|
280
|
+
parts = [part.strip() for part in value.split(";")]
|
|
281
|
+
if not parts or not parts[0].startswith("<"):
|
|
282
|
+
continue
|
|
283
|
+
link = {"url": parts[0].strip("<>")}
|
|
284
|
+
for part in parts[1:]:
|
|
285
|
+
if "=" in part:
|
|
286
|
+
key, item = part.split("=", 1)
|
|
287
|
+
link[key.strip()] = item.strip(' "')
|
|
288
|
+
result[link.get("rel") or link["url"]] = link
|
|
289
|
+
return result
|
|
290
|
+
|
|
291
|
+
def json(self, **kwargs):
|
|
292
|
+
return jsonlib.loads(self.text, **kwargs)
|
|
293
|
+
|
|
294
|
+
def raise_for_status(self):
|
|
295
|
+
if 400 <= self.status_code < 500:
|
|
296
|
+
label = "Client Error"
|
|
297
|
+
elif 500 <= self.status_code < 600:
|
|
298
|
+
label = "Server Error"
|
|
299
|
+
else:
|
|
300
|
+
return None
|
|
301
|
+
message = "%s %s: %s for url: %s" % (
|
|
302
|
+
self.status_code, label, self.reason, self.url,
|
|
303
|
+
)
|
|
304
|
+
raise exceptions.HTTPError(message, response=self, request=self.request)
|
|
305
|
+
|
|
306
|
+
def iter_content(self, chunk_size=1, decode_unicode=False):
|
|
307
|
+
if not isinstance(chunk_size, int) or chunk_size <= 0:
|
|
308
|
+
raise TypeError("chunk_size must be a positive integer")
|
|
309
|
+
for index in range(0, len(self._content), chunk_size):
|
|
310
|
+
chunk = self._content[index:index + chunk_size]
|
|
311
|
+
yield chunk.decode(self.encoding or "utf-8") if decode_unicode else chunk
|
|
312
|
+
|
|
313
|
+
def iter_lines(self, chunk_size=512, decode_unicode=False, delimiter=None):
|
|
314
|
+
data = self.text if decode_unicode else self._content
|
|
315
|
+
for line in data.split(delimiter) if delimiter else data.splitlines():
|
|
316
|
+
yield line
|
|
317
|
+
|
|
318
|
+
def close(self):
|
|
319
|
+
if self.raw is not None:
|
|
320
|
+
self.raw.close()
|
|
321
|
+
|
|
322
|
+
def __enter__(self):
|
|
323
|
+
return self
|
|
324
|
+
|
|
325
|
+
def __exit__(self, *args):
|
|
326
|
+
self.close()
|
|
327
|
+
|
|
328
|
+
def __bool__(self):
|
|
329
|
+
return self.ok
|
|
330
|
+
|
|
331
|
+
__nonzero__ = __bool__
|
|
332
|
+
|
|
333
|
+
def __repr__(self):
|
|
334
|
+
return "<Response [%s]>" % self.status_code
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
class BaseAdapter(object):
|
|
338
|
+
def send(self, request, **kwargs):
|
|
339
|
+
raise NotImplementedError
|
|
340
|
+
|
|
341
|
+
def close(self):
|
|
342
|
+
pass
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class TLSClientAdapter(BaseAdapter):
|
|
346
|
+
def __init__(self, native_session):
|
|
347
|
+
self.native_session = native_session
|
|
348
|
+
self._closed = False
|
|
349
|
+
|
|
350
|
+
def send(self, request, stream=False, timeout=None, verify=True, cert=None,
|
|
351
|
+
proxies=None, **options):
|
|
352
|
+
proxy = options.pop("proxy", None) or _resolve_proxy_url(proxies, request.url)
|
|
353
|
+
options.update(_timeout_options(timeout))
|
|
354
|
+
options.update(body=request.body, follow_redirects=False,
|
|
355
|
+
headers=dict(request.headers.items()), proxy=proxy,
|
|
356
|
+
verify=bool(verify))
|
|
357
|
+
if cert:
|
|
358
|
+
options["client_certificates"] = _load_client_certificates(cert)
|
|
359
|
+
started = time.monotonic()
|
|
360
|
+
try:
|
|
361
|
+
native = self.native_session.execute_request(request.method, request.url, **options)
|
|
362
|
+
except RuntimeError as error:
|
|
363
|
+
raise _transport_error(error, request)
|
|
364
|
+
|
|
365
|
+
response = Response()
|
|
366
|
+
response.status_code = native.status_code
|
|
367
|
+
for name, values in native.headers.items():
|
|
368
|
+
response.headers[name] = ", ".join(str(item) for item in values) \
|
|
369
|
+
if isinstance(values, (list, tuple)) else str(values)
|
|
370
|
+
response._content = native.content
|
|
371
|
+
response.raw = io.BytesIO(native.content)
|
|
372
|
+
response.url = native.url or request.url
|
|
373
|
+
response.reason = native.reason or reason_phrases.get(native.status_code, "")
|
|
374
|
+
response.encoding = _encoding_from_headers(response.headers)
|
|
375
|
+
response.cookies = extract_cookies(native.headers, response.url)
|
|
376
|
+
for name, value in (native.cookies or {}).items():
|
|
377
|
+
if response.cookies.get(name) is None:
|
|
378
|
+
response.cookies.set(name, value)
|
|
379
|
+
response.elapsed = timedelta(seconds=time.monotonic() - started)
|
|
380
|
+
response.request, response.connection = request, self
|
|
381
|
+
response.used_protocol = native.used_protocol
|
|
382
|
+
return response
|
|
383
|
+
|
|
384
|
+
def close(self):
|
|
385
|
+
# The Go client pool is process-global and TTL-evicted; individual
|
|
386
|
+
# sessions do not own pool entries. Calling ClearClientPool() here
|
|
387
|
+
# would evict the clients pooled for every other concurrent session
|
|
388
|
+
# — and the top-level request() helpers close a session on every
|
|
389
|
+
# call, which used to nuke the whole pool under load. Call
|
|
390
|
+
# NativeSession.clear_client_pool() explicitly when a global
|
|
391
|
+
# teardown is really intended.
|
|
392
|
+
self._closed = True
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _encoding_from_headers(headers):
|
|
396
|
+
content_type = headers.get("content-type", "")
|
|
397
|
+
for item in content_type.split(";")[1:]:
|
|
398
|
+
if "=" in item:
|
|
399
|
+
key, value = item.split("=", 1)
|
|
400
|
+
if key.strip().lower() == "charset":
|
|
401
|
+
return value.strip(' "\'')
|
|
402
|
+
return "utf-8" if "application/json" in content_type.lower() else None
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
class Session(object):
|
|
406
|
+
def __init__(self, **options):
|
|
407
|
+
requested_identifier = options.get("client_identifier", "chrome_120")
|
|
408
|
+
if requested_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
|
|
409
|
+
raise ValueError("unsupported client_identifier %r" % requested_identifier)
|
|
410
|
+
native_session = options.pop("_native_session", None)
|
|
411
|
+
initial_headers = options.pop("headers", None)
|
|
412
|
+
initial_cookies = options.pop("cookies", None)
|
|
413
|
+
request_cookies = options.pop("request_cookies", None)
|
|
414
|
+
initial_params = options.pop("params", None)
|
|
415
|
+
initial_auth = options.pop("auth", None)
|
|
416
|
+
initial_proxies = options.pop("proxies", None)
|
|
417
|
+
initial_proxy = options.pop("proxy", None)
|
|
418
|
+
initial_verify = options.pop("verify", True)
|
|
419
|
+
initial_cert = options.pop("cert", None)
|
|
420
|
+
initial_stream = options.pop("stream", False)
|
|
421
|
+
initial_hooks = options.pop("hooks", None)
|
|
422
|
+
initial_max_redirects = options.pop("max_redirects", 30)
|
|
423
|
+
initial_trust_env = options.pop("trust_env", True)
|
|
424
|
+
default_timeout = options.pop("timeout", 30)
|
|
425
|
+
|
|
426
|
+
self.headers = CaseInsensitiveDict(initial_headers or {})
|
|
427
|
+
self.params = dict(initial_params or {})
|
|
428
|
+
self.auth = initial_auth
|
|
429
|
+
self.cookies = RequestsCookieJar()
|
|
430
|
+
self.cookies.update(request_cookies or {})
|
|
431
|
+
self.cookies.update(initial_cookies or {})
|
|
432
|
+
self.proxies = dict(initial_proxies or {})
|
|
433
|
+
if initial_proxy:
|
|
434
|
+
self.proxies.update({"http": initial_proxy, "https": initial_proxy})
|
|
435
|
+
self.hooks = merge_hooks(initial_hooks, None) if initial_hooks else default_hooks()
|
|
436
|
+
self.stream, self.verify, self.cert = initial_stream, initial_verify, initial_cert
|
|
437
|
+
self.max_redirects, self.trust_env = initial_max_redirects, initial_trust_env
|
|
438
|
+
self._default_timeout = default_timeout
|
|
439
|
+
|
|
440
|
+
if native_session is None:
|
|
441
|
+
options.setdefault("without_cookie_jar", True)
|
|
442
|
+
native_session = NativeSession(**options)
|
|
443
|
+
self._native = native_session
|
|
444
|
+
adapter = TLSClientAdapter(native_session)
|
|
445
|
+
self.adapters = {}
|
|
446
|
+
self.mount("http://", adapter)
|
|
447
|
+
self.mount("https://", adapter)
|
|
448
|
+
|
|
449
|
+
def __getattr__(self, name):
|
|
450
|
+
native = self.__dict__.get("_native")
|
|
451
|
+
if native is not None and hasattr(native, name):
|
|
452
|
+
return getattr(native, name)
|
|
453
|
+
raise AttributeError(name)
|
|
454
|
+
|
|
455
|
+
def __setattr__(self, name, value):
|
|
456
|
+
native = self.__dict__.get("_native")
|
|
457
|
+
descriptor = getattr(type(native), name, None) if native is not None else None
|
|
458
|
+
if native is not None and name not in _REQUESTS_ATTRIBUTES and isinstance(descriptor, property):
|
|
459
|
+
setattr(native, name, value)
|
|
460
|
+
if name == "timeout":
|
|
461
|
+
object.__setattr__(self, "_default_timeout", value)
|
|
462
|
+
return
|
|
463
|
+
object.__setattr__(self, name, value)
|
|
464
|
+
|
|
465
|
+
def prepare_request(self, request):
|
|
466
|
+
headers = self.headers.copy()
|
|
467
|
+
headers.update(request.headers or {})
|
|
468
|
+
params = dict(self.params)
|
|
469
|
+
if request.params:
|
|
470
|
+
if hasattr(request.params, "items"):
|
|
471
|
+
params.update(request.params)
|
|
472
|
+
else:
|
|
473
|
+
params = list(params.items()) + list(request.params)
|
|
474
|
+
cookies = self.cookies.copy()
|
|
475
|
+
merge_cookies(cookies, request.cookies)
|
|
476
|
+
return PreparedRequest().prepare(
|
|
477
|
+
method=request.method, url=request.url, headers=headers, files=request.files,
|
|
478
|
+
data=request.data, params=params,
|
|
479
|
+
auth=request.auth if request.auth is not None else self.auth,
|
|
480
|
+
cookies=cookies, hooks=merge_hooks(request.hooks, self.hooks), json=request.json,
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
def request(self, method, url, params=None, data=None, headers=None, cookies=None,
|
|
484
|
+
files=None, auth=None, timeout=None, allow_redirects=True, proxies=None,
|
|
485
|
+
hooks=None, stream=None, verify=None, cert=None, json=None,
|
|
486
|
+
context=None, **kwargs):
|
|
487
|
+
body = kwargs.pop("body", None)
|
|
488
|
+
if body is not None and data is None:
|
|
489
|
+
data = body
|
|
490
|
+
if "follow_redirects" in kwargs:
|
|
491
|
+
allow_redirects = kwargs.pop("follow_redirects")
|
|
492
|
+
tls_options = {}
|
|
493
|
+
for name in list(kwargs):
|
|
494
|
+
if name in _TLS_REQUEST_OPTIONS:
|
|
495
|
+
tls_options[name] = kwargs.pop(name)
|
|
496
|
+
if kwargs:
|
|
497
|
+
raise TypeError("unexpected request argument: %s" % next(iter(kwargs)))
|
|
498
|
+
|
|
499
|
+
prepared = self.prepare_request(Request(
|
|
500
|
+
method, url, headers, files, data, params, auth, cookies, hooks, json,
|
|
501
|
+
))
|
|
502
|
+
send_options = self.merge_environment_settings(prepared.url, proxies, stream, verify, cert)
|
|
503
|
+
send_options.update(allow_redirects=allow_redirects,
|
|
504
|
+
timeout=self._default_timeout if timeout is None else timeout)
|
|
505
|
+
send_options.update(tls_options)
|
|
506
|
+
if context is not None:
|
|
507
|
+
send_options["context"] = context
|
|
508
|
+
return self.send(prepared, **send_options)
|
|
509
|
+
|
|
510
|
+
def send(self, request, **kwargs):
|
|
511
|
+
allow_redirects = kwargs.pop("allow_redirects", True)
|
|
512
|
+
history, current = [], request
|
|
513
|
+
while True:
|
|
514
|
+
response = self.get_adapter(current.url).send(current, **kwargs)
|
|
515
|
+
response = dispatch_hook("response", current.hooks, response, **kwargs)
|
|
516
|
+
self.cookies.update(response.cookies)
|
|
517
|
+
if not response.is_redirect:
|
|
518
|
+
break
|
|
519
|
+
next_request = self._redirect_request(current, response)
|
|
520
|
+
response._next = next_request
|
|
521
|
+
if not allow_redirects:
|
|
522
|
+
break
|
|
523
|
+
history.append(response)
|
|
524
|
+
if len(history) > self.max_redirects:
|
|
525
|
+
raise exceptions.TooManyRedirects(
|
|
526
|
+
"Exceeded %s redirects" % self.max_redirects, response=response,
|
|
527
|
+
)
|
|
528
|
+
current = next_request
|
|
529
|
+
response.history = history
|
|
530
|
+
return response
|
|
531
|
+
|
|
532
|
+
def _redirect_request(self, request, response):
|
|
533
|
+
prepared = request.copy()
|
|
534
|
+
prepared.url = urljoin(response.url, response.headers["location"])
|
|
535
|
+
if response.status_code == 303 or (
|
|
536
|
+
response.status_code == 302 and prepared.method != "HEAD"
|
|
537
|
+
) or (response.status_code == 301 and prepared.method == "POST"):
|
|
538
|
+
prepared.method, prepared.body = "GET", None
|
|
539
|
+
prepared.headers.pop("Content-Length", None)
|
|
540
|
+
prepared.headers.pop("Content-Type", None)
|
|
541
|
+
if urlsplit(request.url).netloc != urlsplit(prepared.url).netloc:
|
|
542
|
+
prepared.headers.pop("Authorization", None)
|
|
543
|
+
prepared.headers.pop("Cookie", None)
|
|
544
|
+
prepared._cookies = self.cookies.copy()
|
|
545
|
+
prepared.prepare_cookies(prepared._cookies)
|
|
546
|
+
return prepared
|
|
547
|
+
|
|
548
|
+
def merge_environment_settings(self, url, proxies, stream, verify, cert):
|
|
549
|
+
merged_proxies = dict(self.proxies)
|
|
550
|
+
if self.trust_env:
|
|
551
|
+
for key, value in getproxies().items():
|
|
552
|
+
merged_proxies.setdefault(key, value)
|
|
553
|
+
if proxies:
|
|
554
|
+
merged_proxies.update(proxies)
|
|
555
|
+
return {
|
|
556
|
+
"proxies": merged_proxies,
|
|
557
|
+
"stream": self.stream if stream is None else stream,
|
|
558
|
+
"verify": self.verify if verify is None else verify,
|
|
559
|
+
"cert": self.cert if cert is None else cert,
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
def mount(self, prefix, adapter):
|
|
563
|
+
self.adapters[prefix] = adapter
|
|
564
|
+
self.adapters = dict(sorted(
|
|
565
|
+
self.adapters.items(), key=lambda item: len(item[0]), reverse=True,
|
|
566
|
+
))
|
|
567
|
+
|
|
568
|
+
def get_adapter(self, url):
|
|
569
|
+
for prefix, adapter in self.adapters.items():
|
|
570
|
+
if url.lower().startswith(prefix.lower()):
|
|
571
|
+
return adapter
|
|
572
|
+
raise exceptions.InvalidSchema("No connection adapter for %r" % url)
|
|
573
|
+
|
|
574
|
+
def get(self, url, **kwargs):
|
|
575
|
+
kwargs.setdefault("allow_redirects", True)
|
|
576
|
+
return self.request("GET", url, **kwargs)
|
|
577
|
+
|
|
578
|
+
def options(self, url, **kwargs):
|
|
579
|
+
kwargs.setdefault("allow_redirects", True)
|
|
580
|
+
return self.request("OPTIONS", url, **kwargs)
|
|
581
|
+
|
|
582
|
+
def head(self, url, **kwargs):
|
|
583
|
+
kwargs.setdefault("allow_redirects", False)
|
|
584
|
+
return self.request("HEAD", url, **kwargs)
|
|
585
|
+
|
|
586
|
+
def post(self, url, data=None, json=None, **kwargs):
|
|
587
|
+
return self.request("POST", url, data=data, json=json, **kwargs)
|
|
588
|
+
|
|
589
|
+
def put(self, url, data=None, **kwargs):
|
|
590
|
+
return self.request("PUT", url, data=data, **kwargs)
|
|
591
|
+
|
|
592
|
+
def patch(self, url, data=None, **kwargs):
|
|
593
|
+
return self.request("PATCH", url, data=data, **kwargs)
|
|
594
|
+
|
|
595
|
+
def delete(self, url, **kwargs):
|
|
596
|
+
return self.request("DELETE", url, **kwargs)
|
|
597
|
+
|
|
598
|
+
def execute_request(self, method, url, **kwargs):
|
|
599
|
+
return self.request(method, url, **kwargs)
|
|
600
|
+
|
|
601
|
+
def typed_request(self, request, **kwargs):
|
|
602
|
+
if isinstance(request, PreparedRequest):
|
|
603
|
+
return self.send(request, **kwargs)
|
|
604
|
+
if isinstance(request, Request):
|
|
605
|
+
return self.send(self.prepare_request(request), **kwargs)
|
|
606
|
+
values = dict(request)
|
|
607
|
+
method, url = values.pop("method"), values.pop("url")
|
|
608
|
+
values.update(kwargs)
|
|
609
|
+
return self.request(method, url, **values)
|
|
610
|
+
|
|
611
|
+
def close(self):
|
|
612
|
+
closed = set()
|
|
613
|
+
for adapter in self.adapters.values():
|
|
614
|
+
if id(adapter) not in closed:
|
|
615
|
+
adapter.close()
|
|
616
|
+
closed.add(id(adapter))
|
|
617
|
+
|
|
618
|
+
def __enter__(self):
|
|
619
|
+
return self
|
|
620
|
+
|
|
621
|
+
def __exit__(self, *args):
|
|
622
|
+
self.close()
|
|
623
|
+
|
|
624
|
+
@staticmethod
|
|
625
|
+
def clear_client_pool():
|
|
626
|
+
NativeSession.clear_client_pool()
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def request(method, url, **kwargs):
|
|
630
|
+
with Session() as session:
|
|
631
|
+
return session.request(method=method, url=url, **kwargs)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def get(url, params=None, **kwargs):
|
|
635
|
+
return request("GET", url, params=params, **kwargs)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def options(url, **kwargs):
|
|
639
|
+
return request("OPTIONS", url, **kwargs)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def head(url, **kwargs):
|
|
643
|
+
kwargs.setdefault("allow_redirects", False)
|
|
644
|
+
return request("HEAD", url, **kwargs)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def post(url, data=None, json=None, **kwargs):
|
|
648
|
+
return request("POST", url, data=data, json=json, **kwargs)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def put(url, data=None, **kwargs):
|
|
652
|
+
return request("PUT", url, data=data, **kwargs)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def patch(url, data=None, **kwargs):
|
|
656
|
+
return request("PATCH", url, data=data, **kwargs)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def delete(url, **kwargs):
|
|
660
|
+
return request("DELETE", url, **kwargs)
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
# ``Session`` intentionally keeps a ``**options`` implementation so Requests
|
|
664
|
+
# attributes can be normalised before constructing the native client. Expose
|
|
665
|
+
# the complete native keyword signature to inspect(), IDEs and ``help()`` so
|
|
666
|
+
# TLS controls are discoverable at the public top level as well.
|
|
667
|
+
_session_signature = inspect.signature(NativeSession)
|
|
668
|
+
_session_parameters = list(_session_signature.parameters.values())
|
|
669
|
+
_session_parameters.extend([
|
|
670
|
+
inspect.Parameter("hooks", inspect.Parameter.KEYWORD_ONLY, default=None),
|
|
671
|
+
inspect.Parameter("max_redirects", inspect.Parameter.KEYWORD_ONLY, default=30),
|
|
672
|
+
inspect.Parameter("trust_env", inspect.Parameter.KEYWORD_ONLY, default=True),
|
|
673
|
+
])
|
|
674
|
+
Session.__signature__ = _session_signature.replace(parameters=_session_parameters)
|