tls-client-python 1.15.1.1__tar.gz → 1.16.0__tar.gz

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.
Files changed (39) hide show
  1. {tls_client_python-1.15.1.1/tls_client_python.egg-info → tls_client_python-1.16.0}/PKG-INFO +57 -7
  2. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/Readme.md +52 -5
  3. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/pyproject.toml +9 -2
  4. tls_client_python-1.16.0/setup.py +35 -0
  5. tls_client_python-1.16.0/tls_client/__init__.py +63 -0
  6. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/_core.py +6 -2
  7. tls_client_python-1.16.0/tls_client/adapters.py +8 -0
  8. tls_client_python-1.16.0/tls_client/auth.py +45 -0
  9. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/bin/tls-client-darwin-amd64.dylib +0 -0
  10. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/bin/tls-client-darwin-arm64.dylib +0 -0
  11. tls_client_python-1.16.0/tls_client/bin/tls-client-linux-386.so +0 -0
  12. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/bin/tls-client-linux-amd64-musl.so +0 -0
  13. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/bin/tls-client-linux-amd64.so +0 -0
  14. tls_client_python-1.16.0/tls_client/bin/tls-client-linux-arm.so +0 -0
  15. tls_client_python-1.16.0/tls_client/bin/tls-client-linux-arm64.so +0 -0
  16. tls_client_python-1.16.0/tls_client/bin/tls-client-windows-386.dll +0 -0
  17. tls_client_python-1.16.0/tls_client/bin/tls-client-windows-amd64.dll +0 -0
  18. tls_client_python-1.16.0/tls_client/cookies.py +189 -0
  19. tls_client_python-1.16.0/tls_client/exceptions.py +91 -0
  20. tls_client_python-1.16.0/tls_client/hooks.py +30 -0
  21. tls_client_python-1.16.0/tls_client/models.py +6 -0
  22. tls_client_python-1.16.0/tls_client/requests_compat.py +640 -0
  23. tls_client_python-1.16.0/tls_client/status_codes.py +45 -0
  24. tls_client_python-1.16.0/tls_client/structures.py +60 -0
  25. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0/tls_client_python.egg-info}/PKG-INFO +57 -7
  26. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client_python.egg-info/SOURCES.txt +12 -0
  27. tls_client_python-1.16.0/tls_client_python.egg-info/requires.txt +7 -0
  28. tls_client_python-1.15.1.1/setup.py +0 -12
  29. tls_client_python-1.15.1.1/tls_client/__init__.py +0 -28
  30. tls_client_python-1.15.1.1/tls_client/bin/tls-client-windows-386.dll +0 -0
  31. tls_client_python-1.15.1.1/tls_client/bin/tls-client-windows-amd64.dll +0 -0
  32. tls_client_python-1.15.1.1/tls_client_python.egg-info/requires.txt +0 -1
  33. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/LICENSE +0 -0
  34. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/MANIFEST.in +0 -0
  35. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/setup.cfg +0 -0
  36. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client/_default_headers.py +0 -0
  37. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client_python.egg-info/dependency_links.txt +0 -0
  38. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client_python.egg-info/not-zip-safe +0 -0
  39. {tls_client_python-1.15.1.1 → tls_client_python-1.16.0}/tls_client_python.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tls-client-python
3
- Version: 1.15.1.1
3
+ Version: 1.16.0
4
4
  Summary: High-performance Python binding for bogdanfinn/tls-client via CFFI – zero-copy, panic-proof, full TLS fingerprint control
5
5
  Author: komAAmok
6
6
  License-Expression: MIT
@@ -28,20 +28,25 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
28
28
  Classifier: Topic :: Internet :: WWW/HTTP
29
29
  Classifier: Topic :: Security
30
30
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
31
- Requires-Python: <=3.14,>=3.6
31
+ Requires-Python: >=3.6,<3.15
32
32
  Description-Content-Type: text/markdown
33
33
  License-File: LICENSE
34
34
  Requires-Dist: cffi>=1.14.0
35
+ Requires-Dist: typing_extensions<4.2,>=4.1; python_version < "3.7"
36
+ Requires-Dist: typing_extensions>=4.1; python_version >= "3.7" and python_version < "3.10"
35
37
  Dynamic: license-file
38
+ Dynamic: requires-python
36
39
 
37
40
  # tls-client-python
38
41
 
42
+ > **维护边界:** Go 引擎同步自上游,本项目的 Python/CFFI 扩展及冲突保留规则见
43
+ > [`UPSTREAM_SYNC.md`](UPSTREAM_SYNC.md)。日常修改请勿直接改动上游归属区域。
44
+
39
45
  [![PyPI version](https://img.shields.io/pypi/v/tls-client-python)](https://pypi.org/project/tls-client-python/)
40
46
  [![Python](https://img.shields.io/pypi/pyversions/tls-client-python)](https://pypi.org/project/tls-client-python/)
41
47
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
42
48
 
43
- **High-performance Python binding for [bogdanfinn/tls-client](https://github.com/bogdanfinn/tls-client) via CFFI.**
44
-
49
+ **CFFI-based, high-performance Python binding for [`tls-client`](https://github.com/bogdanfinn/tls-client) — drop-in compatible with [`requests`](https://github.com/psf/requests) and [`Python-Tls-Client`](https://github.com/FlorianREGAZ/Python-Tls-Client).**
45
50
  ---
46
51
 
47
52
  ## What is TLS Fingerprinting?
@@ -70,6 +75,11 @@ For a deep dive, see [this excellent article on TLS fingerprinting](https://http
70
75
  | 🛡️ **Panic-proof** | All Go panics caught and surfaced as Python exceptions |
71
76
  | ⚙️ **Custom TLS** | Full 26-field custom TLS client configuration |
72
77
 
78
+ > **macOS TCP fingerprinting:** macOS derives TCP MSS during `connect` and
79
+ > rejects `TCP_MAXSEG` in the pre-connect socket hook. The MSS hint is therefore
80
+ > skipped on macOS; TTL, receive-window tuning, and TLS/HTTP fingerprints remain
81
+ > active. This avoids `MSS(1460): invalid argument` on macOS 26 and earlier.
82
+
73
83
  ---
74
84
 
75
85
  ## 📦 Installation
@@ -124,6 +134,42 @@ async def main():
124
134
  asyncio.run(main())
125
135
  ```
126
136
 
137
+ ### Requests-compatible API
138
+
139
+ The synchronous API implements Requests-style request preparation, session
140
+ state, redirects, cookies, hooks, exceptions, and response objects without
141
+ depending on the Requests package. Network transport remains the native
142
+ tls-client engine:
143
+
144
+ ```python
145
+ import tls_client
146
+
147
+ response = tls_client.get(
148
+ "https://example.com/api",
149
+ params={"page": 1},
150
+ headers={"Accept": "application/json"},
151
+ timeout=(3.05, 30),
152
+ )
153
+ response.raise_for_status()
154
+ print(response.json())
155
+
156
+ with tls_client.Session(client_identifier="chrome_146") as session:
157
+ session.headers.update({"Authorization": "Bearer token"})
158
+ response = session.post(
159
+ "https://example.com/upload",
160
+ files={"file": ("data.txt", b"payload")},
161
+ hooks={"response": lambda r, *args, **kwargs: r},
162
+ )
163
+ ```
164
+
165
+ `Request`, `PreparedRequest`, `Response`, `exceptions`, `codes`, `cookies`,
166
+ `auth`, `adapters`, `structures`, and all top-level HTTP helpers follow the
167
+ commonly used Requests API. The previous low-level objects remain available as `NativeSession`,
168
+ `NativeResponse`, and `TLSRequest`. `stream=True` exposes the normal Requests
169
+ iteration API, but the current native ABI buffers the response before Python
170
+ receives it. A string `verify` value enables verification with system roots;
171
+ passing a custom CA bundle through the C ABI is not yet supported.
172
+
127
173
  ---
128
174
 
129
175
  ## 🖥️ Supported Platforms
@@ -321,17 +367,21 @@ resp = s.get("https://tls.browserleaks.com/json", client_identifier="firefox_148
321
367
  | Property / Method | Description |
322
368
  |-------------------|-------------|
323
369
  | `status_code` | HTTP status code (int) |
324
- | `headers` | Response headers (dict of list) |
370
+ | `headers` | Case-insensitive response headers |
325
371
  | `content` | Raw bytes body |
326
372
  | `text` | Decoded text body |
327
373
  | `encoding` | Detected charset |
328
374
  | `url` | Final URL after redirects |
329
- | `cookies` | Response cookies dict |
375
+ | `cookies` | Requests cookie jar |
376
+ | `history` | Redirect response history |
377
+ | `request` | The originating `PreparedRequest` |
378
+ | `raw` | File-like buffered raw response |
330
379
  | `used_protocol` | Protocol used (e.g. `HTTP/2.0`) |
331
380
  | `ok` | `True` if `status_code < 400` |
332
381
  | `reason` | HTTP reason phrase |
333
382
  | `json()` | Parse body as JSON |
334
- | `raise_for_status()` | Raise `RuntimeError` on 4xx/5xx |
383
+ | `raise_for_status()` | Raise `tls_client.exceptions.HTTPError` on 4xx/5xx |
384
+ | `iter_content()` / `iter_lines()` | Iterate over buffered response data |
335
385
 
336
386
  ---
337
387
 
@@ -1,11 +1,13 @@
1
1
  # tls-client-python
2
2
 
3
+ > **维护边界:** Go 引擎同步自上游,本项目的 Python/CFFI 扩展及冲突保留规则见
4
+ > [`UPSTREAM_SYNC.md`](UPSTREAM_SYNC.md)。日常修改请勿直接改动上游归属区域。
5
+
3
6
  [![PyPI version](https://img.shields.io/pypi/v/tls-client-python)](https://pypi.org/project/tls-client-python/)
4
7
  [![Python](https://img.shields.io/pypi/pyversions/tls-client-python)](https://pypi.org/project/tls-client-python/)
5
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
9
 
7
- **High-performance Python binding for [bogdanfinn/tls-client](https://github.com/bogdanfinn/tls-client) via CFFI.**
8
-
10
+ **CFFI-based, high-performance Python binding for [`tls-client`](https://github.com/bogdanfinn/tls-client) — drop-in compatible with [`requests`](https://github.com/psf/requests) and [`Python-Tls-Client`](https://github.com/FlorianREGAZ/Python-Tls-Client).**
9
11
  ---
10
12
 
11
13
  ## What is TLS Fingerprinting?
@@ -34,6 +36,11 @@ For a deep dive, see [this excellent article on TLS fingerprinting](https://http
34
36
  | 🛡️ **Panic-proof** | All Go panics caught and surfaced as Python exceptions |
35
37
  | ⚙️ **Custom TLS** | Full 26-field custom TLS client configuration |
36
38
 
39
+ > **macOS TCP fingerprinting:** macOS derives TCP MSS during `connect` and
40
+ > rejects `TCP_MAXSEG` in the pre-connect socket hook. The MSS hint is therefore
41
+ > skipped on macOS; TTL, receive-window tuning, and TLS/HTTP fingerprints remain
42
+ > active. This avoids `MSS(1460): invalid argument` on macOS 26 and earlier.
43
+
37
44
  ---
38
45
 
39
46
  ## 📦 Installation
@@ -88,6 +95,42 @@ async def main():
88
95
  asyncio.run(main())
89
96
  ```
90
97
 
98
+ ### Requests-compatible API
99
+
100
+ The synchronous API implements Requests-style request preparation, session
101
+ state, redirects, cookies, hooks, exceptions, and response objects without
102
+ depending on the Requests package. Network transport remains the native
103
+ tls-client engine:
104
+
105
+ ```python
106
+ import tls_client
107
+
108
+ response = tls_client.get(
109
+ "https://example.com/api",
110
+ params={"page": 1},
111
+ headers={"Accept": "application/json"},
112
+ timeout=(3.05, 30),
113
+ )
114
+ response.raise_for_status()
115
+ print(response.json())
116
+
117
+ with tls_client.Session(client_identifier="chrome_146") as session:
118
+ session.headers.update({"Authorization": "Bearer token"})
119
+ response = session.post(
120
+ "https://example.com/upload",
121
+ files={"file": ("data.txt", b"payload")},
122
+ hooks={"response": lambda r, *args, **kwargs: r},
123
+ )
124
+ ```
125
+
126
+ `Request`, `PreparedRequest`, `Response`, `exceptions`, `codes`, `cookies`,
127
+ `auth`, `adapters`, `structures`, and all top-level HTTP helpers follow the
128
+ commonly used Requests API. The previous low-level objects remain available as `NativeSession`,
129
+ `NativeResponse`, and `TLSRequest`. `stream=True` exposes the normal Requests
130
+ iteration API, but the current native ABI buffers the response before Python
131
+ receives it. A string `verify` value enables verification with system roots;
132
+ passing a custom CA bundle through the C ABI is not yet supported.
133
+
91
134
  ---
92
135
 
93
136
  ## 🖥️ Supported Platforms
@@ -285,17 +328,21 @@ resp = s.get("https://tls.browserleaks.com/json", client_identifier="firefox_148
285
328
  | Property / Method | Description |
286
329
  |-------------------|-------------|
287
330
  | `status_code` | HTTP status code (int) |
288
- | `headers` | Response headers (dict of list) |
331
+ | `headers` | Case-insensitive response headers |
289
332
  | `content` | Raw bytes body |
290
333
  | `text` | Decoded text body |
291
334
  | `encoding` | Detected charset |
292
335
  | `url` | Final URL after redirects |
293
- | `cookies` | Response cookies dict |
336
+ | `cookies` | Requests cookie jar |
337
+ | `history` | Redirect response history |
338
+ | `request` | The originating `PreparedRequest` |
339
+ | `raw` | File-like buffered raw response |
294
340
  | `used_protocol` | Protocol used (e.g. `HTTP/2.0`) |
295
341
  | `ok` | `True` if `status_code < 400` |
296
342
  | `reason` | HTTP reason phrase |
297
343
  | `json()` | Parse body as JSON |
298
- | `raise_for_status()` | Raise `RuntimeError` on 4xx/5xx |
344
+ | `raise_for_status()` | Raise `tls_client.exceptions.HTTPError` on 4xx/5xx |
345
+ | `iter_content()` / `iter_lines()` | Iterate over buffered response data |
299
346
 
300
347
  ---
301
348
 
@@ -1,5 +1,10 @@
1
1
  [build-system]
2
- requires = ["setuptools>=61.0", "wheel"]
2
+ requires = [
3
+ "setuptools>=44,<59.7; python_version < '3.7'",
4
+ "setuptools>=61; python_version >= '3.7'",
5
+ "wheel<0.38; python_version < '3.7'",
6
+ "wheel; python_version >= '3.7'",
7
+ ]
3
8
  build-backend = "setuptools.build_meta"
4
9
 
5
10
  [project]
@@ -46,10 +51,12 @@ classifiers = [
46
51
  ]
47
52
 
48
53
 
49
- requires-python = ">=3.6, <=3.14"
54
+ requires-python = ">=3.6, <3.15"
50
55
 
51
56
  dependencies = [
52
57
  "cffi>=1.14.0",
58
+ "typing_extensions>=4.1,<4.2; python_version < '3.7'",
59
+ "typing_extensions>=4.1; python_version >= '3.7' and python_version < '3.10'",
53
60
  ]
54
61
 
55
62
 
@@ -0,0 +1,35 @@
1
+ """Legacy build metadata for Python 3.6.
2
+
3
+ Modern Python versions use the PEP 621 metadata in pyproject.toml. Python 3.6
4
+ needs a setuptools release older than PEP 621, so the same essentials live here.
5
+ """
6
+
7
+ from setuptools import setup
8
+ from setuptools.dist import Distribution
9
+
10
+
11
+ class BinaryDistribution(Distribution):
12
+ def is_pure(self):
13
+ return False
14
+
15
+
16
+ setup(
17
+ distclass=BinaryDistribution,
18
+ name="tls-client-python",
19
+ version="1.16.0",
20
+ description="High-performance CFFI binding for bogdanfinn/tls-client",
21
+ long_description=open("Readme.md", "r", encoding="utf-8").read(),
22
+ long_description_content_type="text/markdown",
23
+ license="MIT",
24
+ author="komAAmok",
25
+ packages=["tls_client"],
26
+ package_data={"tls_client": ["bin/*.so", "bin/*.dylib", "bin/*.dll", "py.typed"]},
27
+ include_package_data=True,
28
+ zip_safe=False,
29
+ python_requires=">=3.6,<3.15",
30
+ install_requires=[
31
+ "cffi>=1.14.0",
32
+ "typing_extensions>=4.1,<4.2; python_version<'3.7'",
33
+ "typing_extensions>=4.1; python_version>='3.7' and python_version<'3.10'",
34
+ ],
35
+ )
@@ -0,0 +1,63 @@
1
+ """
2
+ tls_client – High-performance Python binding for
3
+ github.com/bogdanfinn/tls-client via CFFI + platform-native shared library.
4
+
5
+ The package auto‑detects the host OS and architecture at import time,
6
+ selecting the correct pre‑compiled binary from the bundled ``bin/``
7
+ directory. A ``TLS_CLIENT_LIB`` environment variable may be used to
8
+ override automatic discovery.
9
+ """
10
+
11
+ from tls_client._core import AsyncSession, ClientIdentifiers, clear_client_pool
12
+ from tls_client._core import Request as TLSRequest
13
+ from tls_client._core import Response as NativeResponse
14
+ from tls_client._core import Session as NativeSession
15
+ from tls_client.requests_compat import (
16
+ PreparedRequest,
17
+ Request,
18
+ Response,
19
+ Session,
20
+ TLSClientAdapter,
21
+ delete,
22
+ get,
23
+ head,
24
+ options,
25
+ patch,
26
+ post,
27
+ put,
28
+ request,
29
+ )
30
+
31
+ from tls_client import adapters, auth, cookies, exceptions, models, status_codes, structures
32
+ from tls_client.status_codes import codes
33
+
34
+ __all__ = [
35
+ "Session",
36
+ "AsyncSession",
37
+ "Request",
38
+ "PreparedRequest",
39
+ "Response",
40
+ "TLSClientAdapter",
41
+ "NativeSession",
42
+ "NativeResponse",
43
+ "TLSRequest",
44
+ "ClientIdentifiers",
45
+ "clear_client_pool",
46
+ "request",
47
+ "get",
48
+ "options",
49
+ "head",
50
+ "post",
51
+ "put",
52
+ "patch",
53
+ "delete",
54
+ "adapters",
55
+ "auth",
56
+ "codes",
57
+ "cookies",
58
+ "exceptions",
59
+ "models",
60
+ "status_codes",
61
+ "structures",
62
+ ]
63
+ __version__ = "1.16.0"
@@ -48,7 +48,10 @@ try:
48
48
  except ImportError:
49
49
  from typing_extensions import Literal, TypedDict # Python 3.6–3.7
50
50
 
51
- from typing_extensions import TypeAlias # Python <3.10
51
+ try:
52
+ from typing import TypeAlias
53
+ except ImportError:
54
+ from typing_extensions import TypeAlias # Python 3.6-3.9
52
55
 
53
56
 
54
57
  # ---------------------------------------------------------------------------
@@ -3193,7 +3196,8 @@ class AsyncSession:
3193
3196
  raise RuntimeError("AsyncSession is closed")
3194
3197
  ffi, lib = _get_ffi()
3195
3198
  callback = _get_async_callback(ffi, lib)
3196
- loop = asyncio.get_running_loop()
3199
+ get_running_loop = getattr(asyncio, "get_running_loop", asyncio.get_event_loop)
3200
+ loop = get_running_loop()
3197
3201
  defaults = self._session._snapshot_selected_defaults(ASYNC_REQUEST_DEFAULT_KEYS)
3198
3202
  effective_proxy = _resolve_proxy_url(
3199
3203
  kwargs.get("proxy", defaults.get("proxy")),
@@ -0,0 +1,8 @@
1
+ """Transport adapter exports."""
2
+
3
+ from tls_client.requests_compat import BaseAdapter, TLSClientAdapter
4
+
5
+ HTTPAdapter = TLSClientAdapter
6
+
7
+ __all__ = ["BaseAdapter", "HTTPAdapter", "TLSClientAdapter"]
8
+
@@ -0,0 +1,45 @@
1
+ """Authentication helpers compatible with the common Requests API."""
2
+
3
+ import base64
4
+
5
+
6
+ class AuthBase(object):
7
+ def __call__(self, request):
8
+ raise NotImplementedError("authentication classes must implement __call__")
9
+
10
+
11
+ class HTTPBasicAuth(AuthBase):
12
+ def __init__(self, username, password):
13
+ self.username = username
14
+ self.password = password
15
+
16
+ def __call__(self, request):
17
+ raw = ("%s:%s" % (self.username, self.password)).encode("latin1")
18
+ request.headers["Authorization"] = "Basic " + base64.b64encode(raw).decode("ascii")
19
+ return request
20
+
21
+ def __eq__(self, other):
22
+ return (
23
+ isinstance(other, HTTPBasicAuth)
24
+ and self.username == other.username
25
+ and self.password == other.password
26
+ )
27
+
28
+
29
+ class HTTPProxyAuth(HTTPBasicAuth):
30
+ def __call__(self, request):
31
+ raw = ("%s:%s" % (self.username, self.password)).encode("latin1")
32
+ request.headers["Proxy-Authorization"] = (
33
+ "Basic " + base64.b64encode(raw).decode("ascii")
34
+ )
35
+ return request
36
+
37
+
38
+ class HTTPDigestAuth(AuthBase):
39
+ def __init__(self, username, password):
40
+ self.username = username
41
+ self.password = password
42
+
43
+ def __call__(self, request):
44
+ raise NotImplementedError("HTTP Digest authentication requires challenge replay")
45
+
@@ -0,0 +1,189 @@
1
+ """Dependency-free Requests-style cookie jar."""
2
+
3
+ from collections.abc import MutableMapping
4
+ from http.cookies import SimpleCookie
5
+ from urllib.parse import urlsplit
6
+
7
+
8
+ class CookieConflictError(RuntimeError):
9
+ pass
10
+
11
+
12
+ class RequestsCookieJar(MutableMapping):
13
+ def __init__(self):
14
+ self._cookies = {}
15
+
16
+ def set(self, name, value, **kwargs):
17
+ domain = kwargs.get("domain") or ""
18
+ path = kwargs.get("path") or "/"
19
+ key = (domain.lower(), path, str(name))
20
+ if value is None:
21
+ self._cookies.pop(key, None)
22
+ else:
23
+ self._cookies[key] = str(value)
24
+ return value
25
+
26
+ def set_cookie(self, cookie, *args, **kwargs):
27
+ return self.set(
28
+ cookie.name,
29
+ cookie.value,
30
+ domain=getattr(cookie, "domain", ""),
31
+ path=getattr(cookie, "path", "/"),
32
+ )
33
+
34
+ def get(self, name, default=None, domain=None, path=None):
35
+ matches = []
36
+ for (item_domain, item_path, item_name), value in self._cookies.items():
37
+ if item_name != name:
38
+ continue
39
+ if domain is not None and item_domain != domain.lower():
40
+ continue
41
+ if path is not None and item_path != path:
42
+ continue
43
+ matches.append(value)
44
+ if not matches:
45
+ return default
46
+ if len(set(matches)) > 1:
47
+ raise CookieConflictError("multiple cookies exist with name %r" % name)
48
+ return matches[0]
49
+
50
+ def get_dict(self, domain=None, path=None):
51
+ result = {}
52
+ for (item_domain, item_path, name), value in self._cookies.items():
53
+ if domain is not None and item_domain != domain.lower():
54
+ continue
55
+ if path is not None and item_path != path:
56
+ continue
57
+ result[name] = value
58
+ return result
59
+
60
+ def update(self, other=None, **kwargs):
61
+ if isinstance(other, RequestsCookieJar):
62
+ self._cookies.update(other._cookies)
63
+ elif other:
64
+ for name, value in dict(other).items():
65
+ self.set(name, value)
66
+ for name, value in kwargs.items():
67
+ self.set(name, value)
68
+
69
+ def copy(self):
70
+ jar = RequestsCookieJar()
71
+ jar._cookies.update(self._cookies)
72
+ return jar
73
+
74
+ def list_domains(self):
75
+ return sorted(set(key[0] for key in self._cookies))
76
+
77
+ def list_paths(self):
78
+ return sorted(set(key[1] for key in self._cookies))
79
+
80
+ def multiple_domains(self):
81
+ return len(set(key[0] for key in self._cookies)) > 1
82
+
83
+ def clear(self, domain=None, path=None, name=None):
84
+ if domain is None and path is None and name is None:
85
+ self._cookies.clear()
86
+ return
87
+ for key in list(self._cookies):
88
+ item_domain, item_path, item_name = key
89
+ if domain is not None and item_domain != domain.lower():
90
+ continue
91
+ if path is not None and item_path != path:
92
+ continue
93
+ if name is not None and item_name != name:
94
+ continue
95
+ del self._cookies[key]
96
+
97
+ def __getitem__(self, name):
98
+ value = self.get(name)
99
+ if value is None:
100
+ raise KeyError(name)
101
+ return value
102
+
103
+ def __setitem__(self, name, value):
104
+ self.set(name, value)
105
+
106
+ def __delitem__(self, name):
107
+ found = False
108
+ for key in list(self._cookies):
109
+ if key[2] == name:
110
+ del self._cookies[key]
111
+ found = True
112
+ if not found:
113
+ raise KeyError(name)
114
+
115
+ def __iter__(self):
116
+ seen = set()
117
+ for _, _, name in self._cookies:
118
+ if name not in seen:
119
+ seen.add(name)
120
+ yield name
121
+
122
+ def __len__(self):
123
+ return len(set(key[2] for key in self._cookies))
124
+
125
+ def __repr__(self):
126
+ return "<RequestsCookieJar %r>" % self.get_dict()
127
+
128
+
129
+ CookieJar = RequestsCookieJar
130
+
131
+
132
+ def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
133
+ jar = cookiejar or RequestsCookieJar()
134
+ for name, value in (cookie_dict or {}).items():
135
+ if overwrite or jar.get(name) is None:
136
+ jar.set(name, value)
137
+ return jar
138
+
139
+
140
+ def dict_from_cookiejar(jar):
141
+ return jar.get_dict() if hasattr(jar, "get_dict") else dict(jar)
142
+
143
+
144
+ def merge_cookies(cookiejar, cookies):
145
+ cookiejar.update(cookies or {})
146
+ return cookiejar
147
+
148
+
149
+ def cookie_header(jar, url):
150
+ parsed = urlsplit(url)
151
+ host = (parsed.hostname or "").lower()
152
+ path = parsed.path or "/"
153
+ pairs = []
154
+ for (domain, cookie_path, name), value in jar._cookies.items():
155
+ if domain:
156
+ bare_domain = domain.lstrip(".")
157
+ if host != bare_domain and not host.endswith("." + bare_domain):
158
+ continue
159
+ if not path.startswith(cookie_path):
160
+ continue
161
+ pairs.append("%s=%s" % (name, value))
162
+ return "; ".join(pairs)
163
+
164
+
165
+ def extract_cookies(headers, url):
166
+ parsed = urlsplit(url)
167
+ host = (parsed.hostname or "").lower()
168
+ jar = RequestsCookieJar()
169
+ values = []
170
+ for name, value in headers.items():
171
+ if str(name).lower() == "set-cookie":
172
+ values = value
173
+ break
174
+ if not isinstance(values, (list, tuple)):
175
+ values = [values]
176
+ for value in values:
177
+ parsed_cookie = SimpleCookie()
178
+ try:
179
+ parsed_cookie.load(value)
180
+ except Exception:
181
+ continue
182
+ for name, morsel in parsed_cookie.items():
183
+ jar.set(
184
+ name,
185
+ morsel.value,
186
+ domain=morsel["domain"] or host,
187
+ path=morsel["path"] or "/",
188
+ )
189
+ return jar