notify-tls-client 0.1.6__py3-none-any.whl → 2.0.0__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.
- notify_tls_client/__init__.py +2 -2
- notify_tls_client/config/__init__.py +18 -0
- notify_tls_client/config/client_config.py +76 -0
- notify_tls_client/config/client_configuration.py +237 -0
- notify_tls_client/config/recovery_config.py +66 -0
- notify_tls_client/config/rotation_config.py +56 -0
- notify_tls_client/core/client/__init__.py +1 -6
- notify_tls_client/core/client/decorators.py +200 -90
- notify_tls_client/core/client_identifiers_manager.py +44 -0
- notify_tls_client/core/notifytlsclient.py +271 -146
- notify_tls_client/core/proxiesmanager/__init__.py +1 -1
- notify_tls_client/core/proxiesmanager/proxiesmanager.py +79 -67
- notify_tls_client/core/proxiesmanager/proxiesmanagerloader.py +33 -33
- notify_tls_client/tls_client/__init__.py +14 -14
- notify_tls_client/tls_client/__version__.py +10 -10
- notify_tls_client/tls_client/cffi.py +40 -62
- notify_tls_client/tls_client/cookies.py +456 -456
- notify_tls_client/tls_client/dependencies/{tls-client-xgo-1.11.0-darwin-arm64.dylib → tls-client-darwin-amd64-1.12.0.dylib} +0 -0
- notify_tls_client/tls_client/dependencies/tls-client-linux-arm64-1.12.0.so +0 -0
- notify_tls_client/tls_client/dependencies/{tls-client-xgo-1.11.0-linux-amd64.so → tls-client-linux-ubuntu-amd64-1.12.0.so} +0 -0
- notify_tls_client/tls_client/dependencies/{tls-client-windows-1.11.0-64.dll → tls-client-windows-64-1.12.0.dll} +0 -0
- notify_tls_client/tls_client/exceptions.py +2 -2
- notify_tls_client/tls_client/response.py +84 -78
- notify_tls_client/tls_client/sessions.py +524 -513
- notify_tls_client/tls_client/settings.py +69 -69
- notify_tls_client/tls_client/structures.py +74 -74
- notify_tls_client-2.0.0.dist-info/METADATA +38 -0
- notify_tls_client-2.0.0.dist-info/RECORD +32 -0
- {notify_tls_client-0.1.6.dist-info → notify_tls_client-2.0.0.dist-info}/WHEEL +1 -1
- notify_tls_client-0.1.6.dist-info/METADATA +0 -16
- notify_tls_client-0.1.6.dist-info/RECORD +0 -25
- {notify_tls_client-0.1.6.dist-info → notify_tls_client-2.0.0.dist-info}/top_level.txt +0 -0
|
@@ -1,456 +1,456 @@
|
|
|
1
|
-
from .structures import CaseInsensitiveDict
|
|
2
|
-
|
|
3
|
-
from http.cookiejar import CookieJar, Cookie
|
|
4
|
-
from typing import MutableMapping, Union, Any
|
|
5
|
-
from urllib.parse import urlparse, urlunparse
|
|
6
|
-
from http.client import HTTPMessage
|
|
7
|
-
import copy
|
|
8
|
-
|
|
9
|
-
try:
|
|
10
|
-
import threading
|
|
11
|
-
except ImportError:
|
|
12
|
-
import dummy_threading as threading
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
class MockRequest:
|
|
16
|
-
"""
|
|
17
|
-
Mimic a urllib2.Request to get the correct cookie string for the request.
|
|
18
|
-
"""
|
|
19
|
-
|
|
20
|
-
def __init__(self, request_url: str, request_headers: CaseInsensitiveDict):
|
|
21
|
-
self.request_url = request_url
|
|
22
|
-
self.request_headers = request_headers
|
|
23
|
-
self._new_headers = {}
|
|
24
|
-
self.type = urlparse(self.request_url).scheme
|
|
25
|
-
|
|
26
|
-
def get_type(self):
|
|
27
|
-
return self.type
|
|
28
|
-
|
|
29
|
-
def get_host(self):
|
|
30
|
-
return urlparse(self.request_url).netloc
|
|
31
|
-
|
|
32
|
-
def get_origin_req_host(self):
|
|
33
|
-
return self.get_host()
|
|
34
|
-
|
|
35
|
-
def get_full_url(self):
|
|
36
|
-
# Only return the response's URL if the user hadn't set the Host
|
|
37
|
-
# header
|
|
38
|
-
if not self.request_headers.get("Host"):
|
|
39
|
-
return self.request_url
|
|
40
|
-
# If they did set it, retrieve it and reconstruct the expected domain
|
|
41
|
-
host = self.request_headers["Host"]
|
|
42
|
-
parsed = urlparse(self.request_url)
|
|
43
|
-
# Reconstruct the URL as we expect it
|
|
44
|
-
return urlunparse(
|
|
45
|
-
[
|
|
46
|
-
parsed.scheme,
|
|
47
|
-
host,
|
|
48
|
-
parsed.path,
|
|
49
|
-
parsed.params,
|
|
50
|
-
parsed.query,
|
|
51
|
-
parsed.fragment,
|
|
52
|
-
]
|
|
53
|
-
)
|
|
54
|
-
|
|
55
|
-
def is_unverifiable(self):
|
|
56
|
-
return True
|
|
57
|
-
|
|
58
|
-
def has_header(self, name):
|
|
59
|
-
return name in self.request_headers or name in self._new_headers
|
|
60
|
-
|
|
61
|
-
def get_header(self, name, default=None):
|
|
62
|
-
return self.request_headers.get(name, self._new_headers.get(name, default))
|
|
63
|
-
|
|
64
|
-
def add_unredirected_header(self, name, value):
|
|
65
|
-
self._new_headers[name] = value
|
|
66
|
-
|
|
67
|
-
def get_new_headers(self):
|
|
68
|
-
return self._new_headers
|
|
69
|
-
|
|
70
|
-
@property
|
|
71
|
-
def unverifiable(self):
|
|
72
|
-
return self.is_unverifiable()
|
|
73
|
-
|
|
74
|
-
@property
|
|
75
|
-
def origin_req_host(self):
|
|
76
|
-
return self.get_origin_req_host()
|
|
77
|
-
|
|
78
|
-
@property
|
|
79
|
-
def host(self):
|
|
80
|
-
return self.get_host()
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
class MockResponse:
|
|
84
|
-
"""
|
|
85
|
-
Wraps a httplib.HTTPMessage to mimic a urllib.addinfourl.
|
|
86
|
-
The objective is to retrieve the response cookies correctly.
|
|
87
|
-
"""
|
|
88
|
-
|
|
89
|
-
def __init__(self, headers):
|
|
90
|
-
self._headers = headers
|
|
91
|
-
|
|
92
|
-
def info(self):
|
|
93
|
-
return self._headers
|
|
94
|
-
|
|
95
|
-
def getheaders(self, name):
|
|
96
|
-
self._headers.getheaders(name)
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
class CookieConflictError(RuntimeError):
|
|
100
|
-
"""There are two cookies that meet the criteria specified in the cookie jar.
|
|
101
|
-
Use .get and .set and include domain and path args in order to be more specific.
|
|
102
|
-
"""
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
class RequestsCookieJar(CookieJar, MutableMapping):
|
|
106
|
-
""" Origin: requests library (https://github.com/psf/requests)
|
|
107
|
-
Compatibility class; is a cookielib.CookieJar, but exposes a dict
|
|
108
|
-
interface.
|
|
109
|
-
|
|
110
|
-
This is the CookieJar we create by default for requests and sessions that
|
|
111
|
-
don't specify one, since some clients may expect response.cookies and
|
|
112
|
-
session.cookies to support dict operations.
|
|
113
|
-
|
|
114
|
-
Requests does not use the dict interface internally; it's just for
|
|
115
|
-
compatibility with external client code. All requests code should work
|
|
116
|
-
out of the box with externally provided instances of ``CookieJar``, e.g.
|
|
117
|
-
``LWPCookieJar`` and ``FileCookieJar``.
|
|
118
|
-
|
|
119
|
-
Unlike a regular CookieJar, this class is pickleable.
|
|
120
|
-
|
|
121
|
-
.. warning:: dictionary operations that are normally O(1) may be O(n).
|
|
122
|
-
"""
|
|
123
|
-
|
|
124
|
-
def get(self, name, default=None, domain=None, path=None):
|
|
125
|
-
"""Dict-like get() that also supports optional domain and path args in
|
|
126
|
-
order to resolve naming collisions from using one cookie jar over
|
|
127
|
-
multiple domains.
|
|
128
|
-
|
|
129
|
-
.. warning:: operation is O(n), not O(1).
|
|
130
|
-
"""
|
|
131
|
-
try:
|
|
132
|
-
return self._find_no_duplicates(name, domain, path)
|
|
133
|
-
except KeyError:
|
|
134
|
-
return default
|
|
135
|
-
|
|
136
|
-
def set(self, name, value, **kwargs):
|
|
137
|
-
"""Dict-like set() that also supports optional domain and path args in
|
|
138
|
-
order to resolve naming collisions from using one cookie jar over
|
|
139
|
-
multiple domains.
|
|
140
|
-
"""
|
|
141
|
-
# support client code that unsets cookies by assignment of a None value:
|
|
142
|
-
if value is None:
|
|
143
|
-
remove_cookie_by_name(
|
|
144
|
-
self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
|
|
145
|
-
)
|
|
146
|
-
return
|
|
147
|
-
|
|
148
|
-
c = create_cookie(name, value, **kwargs)
|
|
149
|
-
self.set_cookie(c)
|
|
150
|
-
return c
|
|
151
|
-
|
|
152
|
-
def iterkeys(self):
|
|
153
|
-
"""Dict-like iterkeys() that returns an iterator of names of cookies
|
|
154
|
-
from the jar.
|
|
155
|
-
|
|
156
|
-
.. seealso:: itervalues() and iteritems().
|
|
157
|
-
"""
|
|
158
|
-
for cookie in iter(self):
|
|
159
|
-
yield cookie.name
|
|
160
|
-
|
|
161
|
-
def keys(self):
|
|
162
|
-
"""Dict-like keys() that returns a list of names of cookies from the
|
|
163
|
-
jar.
|
|
164
|
-
|
|
165
|
-
.. seealso:: values() and items().
|
|
166
|
-
"""
|
|
167
|
-
return list(self.iterkeys())
|
|
168
|
-
|
|
169
|
-
def itervalues(self):
|
|
170
|
-
"""Dict-like itervalues() that returns an iterator of values of cookies
|
|
171
|
-
from the jar.
|
|
172
|
-
|
|
173
|
-
.. seealso:: iterkeys() and iteritems().
|
|
174
|
-
"""
|
|
175
|
-
for cookie in iter(self):
|
|
176
|
-
yield cookie.value
|
|
177
|
-
|
|
178
|
-
def values(self):
|
|
179
|
-
"""Dict-like values() that returns a list of values of cookies from the
|
|
180
|
-
jar.
|
|
181
|
-
|
|
182
|
-
.. seealso:: keys() and items().
|
|
183
|
-
"""
|
|
184
|
-
return list(self.itervalues())
|
|
185
|
-
|
|
186
|
-
def iteritems(self):
|
|
187
|
-
"""Dict-like iteritems() that returns an iterator of name-value tuples
|
|
188
|
-
from the jar.
|
|
189
|
-
|
|
190
|
-
.. seealso:: iterkeys() and itervalues().
|
|
191
|
-
"""
|
|
192
|
-
for cookie in iter(self):
|
|
193
|
-
yield cookie.name, cookie.value
|
|
194
|
-
|
|
195
|
-
def items(self):
|
|
196
|
-
"""Dict-like items() that returns a list of name-value tuples from the
|
|
197
|
-
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
|
|
198
|
-
vanilla python dict of key value pairs.
|
|
199
|
-
|
|
200
|
-
.. seealso:: keys() and values().
|
|
201
|
-
"""
|
|
202
|
-
return list(self.iteritems())
|
|
203
|
-
|
|
204
|
-
def list_domains(self):
|
|
205
|
-
"""Utility method to list all the domains in the jar."""
|
|
206
|
-
domains = []
|
|
207
|
-
for cookie in iter(self):
|
|
208
|
-
if cookie.domain not in domains:
|
|
209
|
-
domains.append(cookie.domain)
|
|
210
|
-
return domains
|
|
211
|
-
|
|
212
|
-
def list_paths(self):
|
|
213
|
-
"""Utility method to list all the paths in the jar."""
|
|
214
|
-
paths = []
|
|
215
|
-
for cookie in iter(self):
|
|
216
|
-
if cookie.path not in paths:
|
|
217
|
-
paths.append(cookie.path)
|
|
218
|
-
return paths
|
|
219
|
-
|
|
220
|
-
def multiple_domains(self):
|
|
221
|
-
"""Returns True if there are multiple domains in the jar.
|
|
222
|
-
Returns False otherwise.
|
|
223
|
-
|
|
224
|
-
:rtype: bool
|
|
225
|
-
"""
|
|
226
|
-
domains = []
|
|
227
|
-
for cookie in iter(self):
|
|
228
|
-
if cookie.domain is not None and cookie.domain in domains:
|
|
229
|
-
return True
|
|
230
|
-
domains.append(cookie.domain)
|
|
231
|
-
return False # there is only one domain in jar
|
|
232
|
-
|
|
233
|
-
def get_dict(self, domain=None, path=None):
|
|
234
|
-
"""Takes as an argument an optional domain and path and returns a plain
|
|
235
|
-
old Python dict of name-value pairs of cookies that meet the
|
|
236
|
-
requirements.
|
|
237
|
-
|
|
238
|
-
:rtype: dict
|
|
239
|
-
"""
|
|
240
|
-
dictionary = {}
|
|
241
|
-
for cookie in iter(self):
|
|
242
|
-
if (domain is None or cookie.domain == domain) and (
|
|
243
|
-
path is None or cookie.path == path
|
|
244
|
-
):
|
|
245
|
-
dictionary[cookie.name] = cookie.value
|
|
246
|
-
return dictionary
|
|
247
|
-
|
|
248
|
-
def __contains__(self, name):
|
|
249
|
-
try:
|
|
250
|
-
return super().__contains__(name)
|
|
251
|
-
except CookieConflictError:
|
|
252
|
-
return True
|
|
253
|
-
|
|
254
|
-
def __getitem__(self, name):
|
|
255
|
-
"""Dict-like __getitem__() for compatibility with client code. Throws
|
|
256
|
-
exception if there are more than one cookie with name. In that case,
|
|
257
|
-
use the more explicit get() method instead.
|
|
258
|
-
|
|
259
|
-
.. warning:: operation is O(n), not O(1).
|
|
260
|
-
"""
|
|
261
|
-
return self._find_no_duplicates(name)
|
|
262
|
-
|
|
263
|
-
def __setitem__(self, name, value):
|
|
264
|
-
"""Dict-like __setitem__ for compatibility with client code. Throws
|
|
265
|
-
exception if there is already a cookie of that name in the jar. In that
|
|
266
|
-
case, use the more explicit set() method instead.
|
|
267
|
-
"""
|
|
268
|
-
self.set(name, value)
|
|
269
|
-
|
|
270
|
-
def __delitem__(self, name):
|
|
271
|
-
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
|
|
272
|
-
``remove_cookie_by_name()``.
|
|
273
|
-
"""
|
|
274
|
-
remove_cookie_by_name(self, name)
|
|
275
|
-
|
|
276
|
-
def set_cookie(self, cookie, *args, **kwargs):
|
|
277
|
-
if (
|
|
278
|
-
hasattr(cookie.value, "startswith")
|
|
279
|
-
and cookie.value.startswith('"')
|
|
280
|
-
and cookie.value.endswith('"')
|
|
281
|
-
):
|
|
282
|
-
cookie.value = cookie.value.replace('\\"', "")
|
|
283
|
-
return super().set_cookie(cookie, *args, **kwargs)
|
|
284
|
-
|
|
285
|
-
def update(self, other):
|
|
286
|
-
"""Updates this jar with cookies from another CookieJar or dict-like"""
|
|
287
|
-
if isinstance(other, CookieJar):
|
|
288
|
-
for cookie in other:
|
|
289
|
-
self.set_cookie(copy.copy(cookie))
|
|
290
|
-
else:
|
|
291
|
-
super().update(other)
|
|
292
|
-
|
|
293
|
-
def _find(self, name, domain=None, path=None):
|
|
294
|
-
"""Requests uses this method internally to get cookie values.
|
|
295
|
-
|
|
296
|
-
If there are conflicting cookies, _find arbitrarily chooses one.
|
|
297
|
-
See _find_no_duplicates if you want an exception thrown if there are
|
|
298
|
-
conflicting cookies.
|
|
299
|
-
|
|
300
|
-
:param name: a string containing name of cookie
|
|
301
|
-
:param domain: (optional) string containing domain of cookie
|
|
302
|
-
:param path: (optional) string containing path of cookie
|
|
303
|
-
:return: cookie.value
|
|
304
|
-
"""
|
|
305
|
-
for cookie in iter(self):
|
|
306
|
-
if cookie.name == name:
|
|
307
|
-
if domain is None or cookie.domain == domain:
|
|
308
|
-
if path is None or cookie.path == path:
|
|
309
|
-
return cookie.value
|
|
310
|
-
|
|
311
|
-
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
|
|
312
|
-
|
|
313
|
-
def _find_no_duplicates(self, name, domain=None, path=None):
|
|
314
|
-
"""Both ``__get_item__`` and ``get`` call this function: it's never
|
|
315
|
-
used elsewhere in Requests.
|
|
316
|
-
|
|
317
|
-
:param name: a string containing name of cookie
|
|
318
|
-
:param domain: (optional) string containing domain of cookie
|
|
319
|
-
:param path: (optional) string containing path of cookie
|
|
320
|
-
:raises KeyError: if cookie is not found
|
|
321
|
-
:raises CookieConflictError: if there are multiple cookies
|
|
322
|
-
that match name and optionally domain and path
|
|
323
|
-
:return: cookie.value
|
|
324
|
-
"""
|
|
325
|
-
toReturn = None
|
|
326
|
-
for cookie in iter(self):
|
|
327
|
-
if cookie.name == name:
|
|
328
|
-
if domain is None or cookie.domain == domain:
|
|
329
|
-
if path is None or cookie.path == path:
|
|
330
|
-
if toReturn is not None:
|
|
331
|
-
# if there are multiple cookies that meet passed in criteria
|
|
332
|
-
raise CookieConflictError(
|
|
333
|
-
f"There are multiple cookies with name, {name!r}"
|
|
334
|
-
)
|
|
335
|
-
# we will eventually return this as long as no cookie conflict
|
|
336
|
-
toReturn = cookie.value
|
|
337
|
-
|
|
338
|
-
if toReturn:
|
|
339
|
-
return toReturn
|
|
340
|
-
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
|
|
341
|
-
|
|
342
|
-
def __getstate__(self):
|
|
343
|
-
"""Unlike a normal CookieJar, this class is pickleable."""
|
|
344
|
-
state = self.__dict__.copy()
|
|
345
|
-
# remove the unpickleable RLock object
|
|
346
|
-
state.pop("_cookies_lock")
|
|
347
|
-
return state
|
|
348
|
-
|
|
349
|
-
def __setstate__(self, state):
|
|
350
|
-
"""Unlike a normal CookieJar, this class is pickleable."""
|
|
351
|
-
self.__dict__.update(state)
|
|
352
|
-
if "_cookies_lock" not in self.__dict__:
|
|
353
|
-
self._cookies_lock = threading.RLock()
|
|
354
|
-
|
|
355
|
-
def copy(self):
|
|
356
|
-
"""Return a copy of this RequestsCookieJar."""
|
|
357
|
-
new_cj = RequestsCookieJar()
|
|
358
|
-
new_cj.set_policy(self.get_policy())
|
|
359
|
-
new_cj.update(self)
|
|
360
|
-
return new_cj
|
|
361
|
-
|
|
362
|
-
def get_policy(self):
|
|
363
|
-
"""Return the CookiePolicy instance used."""
|
|
364
|
-
return self._policy
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
def remove_cookie_by_name(cookiejar: RequestsCookieJar, name: str, domain: str = None, path: str = None):
|
|
368
|
-
"""Removes a cookie by name, by default over all domains and paths."""
|
|
369
|
-
clearables = []
|
|
370
|
-
for cookie in cookiejar:
|
|
371
|
-
if cookie.name != name:
|
|
372
|
-
continue
|
|
373
|
-
if domain is not None and domain != cookie.domain:
|
|
374
|
-
continue
|
|
375
|
-
if path is not None and path != cookie.path:
|
|
376
|
-
continue
|
|
377
|
-
clearables.append((cookie.domain, cookie.path, cookie.name))
|
|
378
|
-
|
|
379
|
-
for domain, path, name in clearables:
|
|
380
|
-
cookiejar.clear(domain, path, name)
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:
|
|
384
|
-
"""Make a cookie from underspecified parameters."""
|
|
385
|
-
result = {
|
|
386
|
-
"version": 0,
|
|
387
|
-
"name": name,
|
|
388
|
-
"value": value,
|
|
389
|
-
"port": None,
|
|
390
|
-
"domain": "",
|
|
391
|
-
"path": "/",
|
|
392
|
-
"secure": False,
|
|
393
|
-
"expires": None,
|
|
394
|
-
"discard": True,
|
|
395
|
-
"comment": None,
|
|
396
|
-
"comment_url": None,
|
|
397
|
-
"rest": {"HttpOnly": None},
|
|
398
|
-
"rfc2109": False,
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
badargs = set(kwargs) - set(result)
|
|
402
|
-
if badargs:
|
|
403
|
-
raise TypeError(
|
|
404
|
-
f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
|
|
405
|
-
)
|
|
406
|
-
|
|
407
|
-
result.update(kwargs)
|
|
408
|
-
result["port_specified"] = bool(result["port"])
|
|
409
|
-
result["domain_specified"] = bool(result["domain"])
|
|
410
|
-
result["domain_initial_dot"] = result["domain"].startswith(".")
|
|
411
|
-
result["path_specified"] = bool(result["path"])
|
|
412
|
-
|
|
413
|
-
return Cookie(**result)
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
def cookiejar_from_dict(cookie_dict: dict) -> RequestsCookieJar:
|
|
417
|
-
"""transform a dict to CookieJar"""
|
|
418
|
-
cookie_jar = RequestsCookieJar()
|
|
419
|
-
if cookie_dict is not None:
|
|
420
|
-
for name, value in cookie_dict.items():
|
|
421
|
-
cookie_jar.set_cookie(create_cookie(name=name, value=value))
|
|
422
|
-
return cookie_jar
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
def merge_cookies(cookiejar: RequestsCookieJar, cookies: Union[dict, RequestsCookieJar]) -> RequestsCookieJar:
|
|
426
|
-
"""Merge cookies in session and cookies provided in request"""
|
|
427
|
-
if type(cookies) is dict:
|
|
428
|
-
cookies = cookiejar_from_dict(cookies)
|
|
429
|
-
|
|
430
|
-
for cookie in cookies:
|
|
431
|
-
cookiejar.set_cookie(cookie)
|
|
432
|
-
|
|
433
|
-
return cookiejar
|
|
434
|
-
|
|
435
|
-
def extract_cookies_to_jar(
|
|
436
|
-
request_url: str,
|
|
437
|
-
request_headers: CaseInsensitiveDict,
|
|
438
|
-
cookie_jar: RequestsCookieJar,
|
|
439
|
-
response_headers: dict
|
|
440
|
-
) -> RequestsCookieJar:
|
|
441
|
-
response_cookie_jar = cookiejar_from_dict({})
|
|
442
|
-
|
|
443
|
-
req = MockRequest(request_url, request_headers)
|
|
444
|
-
# mimic HTTPMessage
|
|
445
|
-
http_message = HTTPMessage()
|
|
446
|
-
http_message._headers = []
|
|
447
|
-
for header_name, header_values in response_headers.items():
|
|
448
|
-
for header_value in header_values:
|
|
449
|
-
http_message._headers.append(
|
|
450
|
-
(header_name, header_value)
|
|
451
|
-
)
|
|
452
|
-
res = MockResponse(http_message)
|
|
453
|
-
response_cookie_jar.extract_cookies(res, req)
|
|
454
|
-
|
|
455
|
-
merge_cookies(cookie_jar, response_cookie_jar)
|
|
456
|
-
return response_cookie_jar
|
|
1
|
+
from .structures import CaseInsensitiveDict
|
|
2
|
+
|
|
3
|
+
from http.cookiejar import CookieJar, Cookie
|
|
4
|
+
from typing import MutableMapping, Union, Any
|
|
5
|
+
from urllib.parse import urlparse, urlunparse
|
|
6
|
+
from http.client import HTTPMessage
|
|
7
|
+
import copy
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import threading
|
|
11
|
+
except ImportError:
|
|
12
|
+
import dummy_threading as threading
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MockRequest:
|
|
16
|
+
"""
|
|
17
|
+
Mimic a urllib2.Request to get the correct cookie string for the request.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, request_url: str, request_headers: CaseInsensitiveDict):
|
|
21
|
+
self.request_url = request_url
|
|
22
|
+
self.request_headers = request_headers
|
|
23
|
+
self._new_headers = {}
|
|
24
|
+
self.type = urlparse(self.request_url).scheme
|
|
25
|
+
|
|
26
|
+
def get_type(self):
|
|
27
|
+
return self.type
|
|
28
|
+
|
|
29
|
+
def get_host(self):
|
|
30
|
+
return urlparse(self.request_url).netloc
|
|
31
|
+
|
|
32
|
+
def get_origin_req_host(self):
|
|
33
|
+
return self.get_host()
|
|
34
|
+
|
|
35
|
+
def get_full_url(self):
|
|
36
|
+
# Only return the response's URL if the user hadn't set the Host
|
|
37
|
+
# header
|
|
38
|
+
if not self.request_headers.get("Host"):
|
|
39
|
+
return self.request_url
|
|
40
|
+
# If they did set it, retrieve it and reconstruct the expected domain
|
|
41
|
+
host = self.request_headers["Host"]
|
|
42
|
+
parsed = urlparse(self.request_url)
|
|
43
|
+
# Reconstruct the URL as we expect it
|
|
44
|
+
return urlunparse(
|
|
45
|
+
[
|
|
46
|
+
parsed.scheme,
|
|
47
|
+
host,
|
|
48
|
+
parsed.path,
|
|
49
|
+
parsed.params,
|
|
50
|
+
parsed.query,
|
|
51
|
+
parsed.fragment,
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def is_unverifiable(self):
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
def has_header(self, name):
|
|
59
|
+
return name in self.request_headers or name in self._new_headers
|
|
60
|
+
|
|
61
|
+
def get_header(self, name, default=None):
|
|
62
|
+
return self.request_headers.get(name, self._new_headers.get(name, default))
|
|
63
|
+
|
|
64
|
+
def add_unredirected_header(self, name, value):
|
|
65
|
+
self._new_headers[name] = value
|
|
66
|
+
|
|
67
|
+
def get_new_headers(self):
|
|
68
|
+
return self._new_headers
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def unverifiable(self):
|
|
72
|
+
return self.is_unverifiable()
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def origin_req_host(self):
|
|
76
|
+
return self.get_origin_req_host()
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def host(self):
|
|
80
|
+
return self.get_host()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class MockResponse:
|
|
84
|
+
"""
|
|
85
|
+
Wraps a httplib.HTTPMessage to mimic a urllib.addinfourl.
|
|
86
|
+
The objective is to retrieve the response cookies correctly.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, headers):
|
|
90
|
+
self._headers = headers
|
|
91
|
+
|
|
92
|
+
def info(self):
|
|
93
|
+
return self._headers
|
|
94
|
+
|
|
95
|
+
def getheaders(self, name):
|
|
96
|
+
self._headers.getheaders(name)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class CookieConflictError(RuntimeError):
|
|
100
|
+
"""There are two cookies that meet the criteria specified in the cookie jar.
|
|
101
|
+
Use .get and .set and include domain and path args in order to be more specific.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class RequestsCookieJar(CookieJar, MutableMapping):
|
|
106
|
+
""" Origin: requests library (https://github.com/psf/requests)
|
|
107
|
+
Compatibility class; is a cookielib.CookieJar, but exposes a dict
|
|
108
|
+
interface.
|
|
109
|
+
|
|
110
|
+
This is the CookieJar we create by default for requests and sessions that
|
|
111
|
+
don't specify one, since some clients may expect response.cookies and
|
|
112
|
+
session.cookies to support dict operations.
|
|
113
|
+
|
|
114
|
+
Requests does not use the dict interface internally; it's just for
|
|
115
|
+
compatibility with external client code. All requests code should work
|
|
116
|
+
out of the box with externally provided instances of ``CookieJar``, e.g.
|
|
117
|
+
``LWPCookieJar`` and ``FileCookieJar``.
|
|
118
|
+
|
|
119
|
+
Unlike a regular CookieJar, this class is pickleable.
|
|
120
|
+
|
|
121
|
+
.. warning:: dictionary operations that are normally O(1) may be O(n).
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def get(self, name, default=None, domain=None, path=None):
|
|
125
|
+
"""Dict-like get() that also supports optional domain and path args in
|
|
126
|
+
order to resolve naming collisions from using one cookie jar over
|
|
127
|
+
multiple domains.
|
|
128
|
+
|
|
129
|
+
.. warning:: operation is O(n), not O(1).
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
return self._find_no_duplicates(name, domain, path)
|
|
133
|
+
except KeyError:
|
|
134
|
+
return default
|
|
135
|
+
|
|
136
|
+
def set(self, name, value, **kwargs):
|
|
137
|
+
"""Dict-like set() that also supports optional domain and path args in
|
|
138
|
+
order to resolve naming collisions from using one cookie jar over
|
|
139
|
+
multiple domains.
|
|
140
|
+
"""
|
|
141
|
+
# support client code that unsets cookies by assignment of a None value:
|
|
142
|
+
if value is None:
|
|
143
|
+
remove_cookie_by_name(
|
|
144
|
+
self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
|
|
145
|
+
)
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
c = create_cookie(name, value, **kwargs)
|
|
149
|
+
self.set_cookie(c)
|
|
150
|
+
return c
|
|
151
|
+
|
|
152
|
+
def iterkeys(self):
|
|
153
|
+
"""Dict-like iterkeys() that returns an iterator of names of cookies
|
|
154
|
+
from the jar.
|
|
155
|
+
|
|
156
|
+
.. seealso:: itervalues() and iteritems().
|
|
157
|
+
"""
|
|
158
|
+
for cookie in iter(self):
|
|
159
|
+
yield cookie.name
|
|
160
|
+
|
|
161
|
+
def keys(self):
|
|
162
|
+
"""Dict-like keys() that returns a list of names of cookies from the
|
|
163
|
+
jar.
|
|
164
|
+
|
|
165
|
+
.. seealso:: values() and items().
|
|
166
|
+
"""
|
|
167
|
+
return list(self.iterkeys())
|
|
168
|
+
|
|
169
|
+
def itervalues(self):
|
|
170
|
+
"""Dict-like itervalues() that returns an iterator of values of cookies
|
|
171
|
+
from the jar.
|
|
172
|
+
|
|
173
|
+
.. seealso:: iterkeys() and iteritems().
|
|
174
|
+
"""
|
|
175
|
+
for cookie in iter(self):
|
|
176
|
+
yield cookie.value
|
|
177
|
+
|
|
178
|
+
def values(self):
|
|
179
|
+
"""Dict-like values() that returns a list of values of cookies from the
|
|
180
|
+
jar.
|
|
181
|
+
|
|
182
|
+
.. seealso:: keys() and items().
|
|
183
|
+
"""
|
|
184
|
+
return list(self.itervalues())
|
|
185
|
+
|
|
186
|
+
def iteritems(self):
|
|
187
|
+
"""Dict-like iteritems() that returns an iterator of name-value tuples
|
|
188
|
+
from the jar.
|
|
189
|
+
|
|
190
|
+
.. seealso:: iterkeys() and itervalues().
|
|
191
|
+
"""
|
|
192
|
+
for cookie in iter(self):
|
|
193
|
+
yield cookie.name, cookie.value
|
|
194
|
+
|
|
195
|
+
def items(self):
|
|
196
|
+
"""Dict-like items() that returns a list of name-value tuples from the
|
|
197
|
+
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
|
|
198
|
+
vanilla python dict of key value pairs.
|
|
199
|
+
|
|
200
|
+
.. seealso:: keys() and values().
|
|
201
|
+
"""
|
|
202
|
+
return list(self.iteritems())
|
|
203
|
+
|
|
204
|
+
def list_domains(self):
|
|
205
|
+
"""Utility method to list all the domains in the jar."""
|
|
206
|
+
domains = []
|
|
207
|
+
for cookie in iter(self):
|
|
208
|
+
if cookie.domain not in domains:
|
|
209
|
+
domains.append(cookie.domain)
|
|
210
|
+
return domains
|
|
211
|
+
|
|
212
|
+
def list_paths(self):
|
|
213
|
+
"""Utility method to list all the paths in the jar."""
|
|
214
|
+
paths = []
|
|
215
|
+
for cookie in iter(self):
|
|
216
|
+
if cookie.path not in paths:
|
|
217
|
+
paths.append(cookie.path)
|
|
218
|
+
return paths
|
|
219
|
+
|
|
220
|
+
def multiple_domains(self):
|
|
221
|
+
"""Returns True if there are multiple domains in the jar.
|
|
222
|
+
Returns False otherwise.
|
|
223
|
+
|
|
224
|
+
:rtype: bool
|
|
225
|
+
"""
|
|
226
|
+
domains = []
|
|
227
|
+
for cookie in iter(self):
|
|
228
|
+
if cookie.domain is not None and cookie.domain in domains:
|
|
229
|
+
return True
|
|
230
|
+
domains.append(cookie.domain)
|
|
231
|
+
return False # there is only one domain in jar
|
|
232
|
+
|
|
233
|
+
def get_dict(self, domain=None, path=None):
|
|
234
|
+
"""Takes as an argument an optional domain and path and returns a plain
|
|
235
|
+
old Python dict of name-value pairs of cookies that meet the
|
|
236
|
+
requirements.
|
|
237
|
+
|
|
238
|
+
:rtype: dict
|
|
239
|
+
"""
|
|
240
|
+
dictionary = {}
|
|
241
|
+
for cookie in iter(self):
|
|
242
|
+
if (domain is None or cookie.domain == domain) and (
|
|
243
|
+
path is None or cookie.path == path
|
|
244
|
+
):
|
|
245
|
+
dictionary[cookie.name] = cookie.value
|
|
246
|
+
return dictionary
|
|
247
|
+
|
|
248
|
+
def __contains__(self, name):
|
|
249
|
+
try:
|
|
250
|
+
return super().__contains__(name)
|
|
251
|
+
except CookieConflictError:
|
|
252
|
+
return True
|
|
253
|
+
|
|
254
|
+
def __getitem__(self, name):
|
|
255
|
+
"""Dict-like __getitem__() for compatibility with client code. Throws
|
|
256
|
+
exception if there are more than one cookie with name. In that case,
|
|
257
|
+
use the more explicit get() method instead.
|
|
258
|
+
|
|
259
|
+
.. warning:: operation is O(n), not O(1).
|
|
260
|
+
"""
|
|
261
|
+
return self._find_no_duplicates(name)
|
|
262
|
+
|
|
263
|
+
def __setitem__(self, name, value):
|
|
264
|
+
"""Dict-like __setitem__ for compatibility with client code. Throws
|
|
265
|
+
exception if there is already a cookie of that name in the jar. In that
|
|
266
|
+
case, use the more explicit set() method instead.
|
|
267
|
+
"""
|
|
268
|
+
self.set(name, value)
|
|
269
|
+
|
|
270
|
+
def __delitem__(self, name):
|
|
271
|
+
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
|
|
272
|
+
``remove_cookie_by_name()``.
|
|
273
|
+
"""
|
|
274
|
+
remove_cookie_by_name(self, name)
|
|
275
|
+
|
|
276
|
+
def set_cookie(self, cookie, *args, **kwargs):
|
|
277
|
+
if (
|
|
278
|
+
hasattr(cookie.value, "startswith")
|
|
279
|
+
and cookie.value.startswith('"')
|
|
280
|
+
and cookie.value.endswith('"')
|
|
281
|
+
):
|
|
282
|
+
cookie.value = cookie.value.replace('\\"', "")
|
|
283
|
+
return super().set_cookie(cookie, *args, **kwargs)
|
|
284
|
+
|
|
285
|
+
def update(self, other):
|
|
286
|
+
"""Updates this jar with cookies from another CookieJar or dict-like"""
|
|
287
|
+
if isinstance(other, CookieJar):
|
|
288
|
+
for cookie in other:
|
|
289
|
+
self.set_cookie(copy.copy(cookie))
|
|
290
|
+
else:
|
|
291
|
+
super().update(other)
|
|
292
|
+
|
|
293
|
+
def _find(self, name, domain=None, path=None):
|
|
294
|
+
"""Requests uses this method internally to get cookie values.
|
|
295
|
+
|
|
296
|
+
If there are conflicting cookies, _find arbitrarily chooses one.
|
|
297
|
+
See _find_no_duplicates if you want an exception thrown if there are
|
|
298
|
+
conflicting cookies.
|
|
299
|
+
|
|
300
|
+
:param name: a string containing name of cookie
|
|
301
|
+
:param domain: (optional) string containing domain of cookie
|
|
302
|
+
:param path: (optional) string containing path of cookie
|
|
303
|
+
:return: cookie.value
|
|
304
|
+
"""
|
|
305
|
+
for cookie in iter(self):
|
|
306
|
+
if cookie.name == name:
|
|
307
|
+
if domain is None or cookie.domain == domain:
|
|
308
|
+
if path is None or cookie.path == path:
|
|
309
|
+
return cookie.value
|
|
310
|
+
|
|
311
|
+
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
|
|
312
|
+
|
|
313
|
+
def _find_no_duplicates(self, name, domain=None, path=None):
|
|
314
|
+
"""Both ``__get_item__`` and ``get`` call this function: it's never
|
|
315
|
+
used elsewhere in Requests.
|
|
316
|
+
|
|
317
|
+
:param name: a string containing name of cookie
|
|
318
|
+
:param domain: (optional) string containing domain of cookie
|
|
319
|
+
:param path: (optional) string containing path of cookie
|
|
320
|
+
:raises KeyError: if cookie is not found
|
|
321
|
+
:raises CookieConflictError: if there are multiple cookies
|
|
322
|
+
that match name and optionally domain and path
|
|
323
|
+
:return: cookie.value
|
|
324
|
+
"""
|
|
325
|
+
toReturn = None
|
|
326
|
+
for cookie in iter(self):
|
|
327
|
+
if cookie.name == name:
|
|
328
|
+
if domain is None or cookie.domain == domain:
|
|
329
|
+
if path is None or cookie.path == path:
|
|
330
|
+
if toReturn is not None:
|
|
331
|
+
# if there are multiple cookies that meet passed in criteria
|
|
332
|
+
raise CookieConflictError(
|
|
333
|
+
f"There are multiple cookies with name, {name!r}"
|
|
334
|
+
)
|
|
335
|
+
# we will eventually return this as long as no cookie conflict
|
|
336
|
+
toReturn = cookie.value
|
|
337
|
+
|
|
338
|
+
if toReturn:
|
|
339
|
+
return toReturn
|
|
340
|
+
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
|
|
341
|
+
|
|
342
|
+
def __getstate__(self):
|
|
343
|
+
"""Unlike a normal CookieJar, this class is pickleable."""
|
|
344
|
+
state = self.__dict__.copy()
|
|
345
|
+
# remove the unpickleable RLock object
|
|
346
|
+
state.pop("_cookies_lock")
|
|
347
|
+
return state
|
|
348
|
+
|
|
349
|
+
def __setstate__(self, state):
|
|
350
|
+
"""Unlike a normal CookieJar, this class is pickleable."""
|
|
351
|
+
self.__dict__.update(state)
|
|
352
|
+
if "_cookies_lock" not in self.__dict__:
|
|
353
|
+
self._cookies_lock = threading.RLock()
|
|
354
|
+
|
|
355
|
+
def copy(self):
|
|
356
|
+
"""Return a copy of this RequestsCookieJar."""
|
|
357
|
+
new_cj = RequestsCookieJar()
|
|
358
|
+
new_cj.set_policy(self.get_policy())
|
|
359
|
+
new_cj.update(self)
|
|
360
|
+
return new_cj
|
|
361
|
+
|
|
362
|
+
def get_policy(self):
|
|
363
|
+
"""Return the CookiePolicy instance used."""
|
|
364
|
+
return self._policy
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def remove_cookie_by_name(cookiejar: RequestsCookieJar, name: str, domain: str = None, path: str = None):
|
|
368
|
+
"""Removes a cookie by name, by default over all domains and paths."""
|
|
369
|
+
clearables = []
|
|
370
|
+
for cookie in cookiejar:
|
|
371
|
+
if cookie.name != name:
|
|
372
|
+
continue
|
|
373
|
+
if domain is not None and domain != cookie.domain:
|
|
374
|
+
continue
|
|
375
|
+
if path is not None and path != cookie.path:
|
|
376
|
+
continue
|
|
377
|
+
clearables.append((cookie.domain, cookie.path, cookie.name))
|
|
378
|
+
|
|
379
|
+
for domain, path, name in clearables:
|
|
380
|
+
cookiejar.clear(domain, path, name)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie:
|
|
384
|
+
"""Make a cookie from underspecified parameters."""
|
|
385
|
+
result = {
|
|
386
|
+
"version": 0,
|
|
387
|
+
"name": name,
|
|
388
|
+
"value": value,
|
|
389
|
+
"port": None,
|
|
390
|
+
"domain": "",
|
|
391
|
+
"path": "/",
|
|
392
|
+
"secure": False,
|
|
393
|
+
"expires": None,
|
|
394
|
+
"discard": True,
|
|
395
|
+
"comment": None,
|
|
396
|
+
"comment_url": None,
|
|
397
|
+
"rest": {"HttpOnly": None},
|
|
398
|
+
"rfc2109": False,
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
badargs = set(kwargs) - set(result)
|
|
402
|
+
if badargs:
|
|
403
|
+
raise TypeError(
|
|
404
|
+
f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
result.update(kwargs)
|
|
408
|
+
result["port_specified"] = bool(result["port"])
|
|
409
|
+
result["domain_specified"] = bool(result["domain"])
|
|
410
|
+
result["domain_initial_dot"] = result["domain"].startswith(".")
|
|
411
|
+
result["path_specified"] = bool(result["path"])
|
|
412
|
+
|
|
413
|
+
return Cookie(**result)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def cookiejar_from_dict(cookie_dict: dict) -> RequestsCookieJar:
|
|
417
|
+
"""transform a dict to CookieJar"""
|
|
418
|
+
cookie_jar = RequestsCookieJar()
|
|
419
|
+
if cookie_dict is not None:
|
|
420
|
+
for name, value in cookie_dict.items():
|
|
421
|
+
cookie_jar.set_cookie(create_cookie(name=name, value=value))
|
|
422
|
+
return cookie_jar
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def merge_cookies(cookiejar: RequestsCookieJar, cookies: Union[dict, RequestsCookieJar]) -> RequestsCookieJar:
|
|
426
|
+
"""Merge cookies in session and cookies provided in request"""
|
|
427
|
+
if type(cookies) is dict:
|
|
428
|
+
cookies = cookiejar_from_dict(cookies)
|
|
429
|
+
|
|
430
|
+
for cookie in cookies:
|
|
431
|
+
cookiejar.set_cookie(cookie)
|
|
432
|
+
|
|
433
|
+
return cookiejar
|
|
434
|
+
|
|
435
|
+
def extract_cookies_to_jar(
|
|
436
|
+
request_url: str,
|
|
437
|
+
request_headers: CaseInsensitiveDict,
|
|
438
|
+
cookie_jar: RequestsCookieJar,
|
|
439
|
+
response_headers: dict
|
|
440
|
+
) -> RequestsCookieJar:
|
|
441
|
+
response_cookie_jar = cookiejar_from_dict({})
|
|
442
|
+
|
|
443
|
+
req = MockRequest(request_url, request_headers)
|
|
444
|
+
# mimic HTTPMessage
|
|
445
|
+
http_message = HTTPMessage()
|
|
446
|
+
http_message._headers = []
|
|
447
|
+
for header_name, header_values in response_headers.items():
|
|
448
|
+
for header_value in header_values:
|
|
449
|
+
http_message._headers.append(
|
|
450
|
+
(header_name, header_value)
|
|
451
|
+
)
|
|
452
|
+
res = MockResponse(http_message)
|
|
453
|
+
response_cookie_jar.extract_cookies(res, req)
|
|
454
|
+
|
|
455
|
+
merge_cookies(cookie_jar, response_cookie_jar)
|
|
456
|
+
return response_cookie_jar
|