Soptq commited on
Commit
aafbe92
·
verified ·
1 Parent(s): ec6431a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected_4Classes/1908276_cm.tif +3 -0
  3. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__init__.py +105 -0
  4. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/__version__.cpython-310.pyc +0 -0
  5. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_auth.cpython-310.pyc +0 -0
  6. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_decoders.cpython-310.pyc +0 -0
  7. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_utils.cpython-310.pyc +0 -0
  8. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_auth.py +348 -0
  9. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_client.py +2019 -0
  10. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_decoders.py +393 -0
  11. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_exceptions.py +379 -0
  12. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_main.py +506 -0
  13. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_multipart.py +300 -0
  14. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_urls.py +641 -0
  15. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_utils.py +242 -0
  16. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/py.typed +0 -0
  17. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/__main__.cpython-310.pyc +0 -0
  18. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/_compatibility.cpython-310.pyc +0 -0
  19. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/debug.cpython-310.pyc +0 -0
  20. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/completion_cache.cpython-310.pyc +0 -0
  21. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/environment.cpython-310.pyc +0 -0
  22. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/exceptions.cpython-310.pyc +0 -0
  23. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/helpers.cpython-310.pyc +0 -0
  24. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/keywords.cpython-310.pyc +0 -0
  25. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/project.cpython-310.pyc +0 -0
  26. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/strings.cpython-310.pyc +0 -0
  27. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/inference/finder.py +146 -0
  28. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/contrib/admin/views/main.pyi +89 -0
  29. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/__init__.pyi +0 -0
  30. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/base.pyi +17 -0
  31. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/client.pyi +9 -0
  32. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/creation.pyi +3 -0
  33. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/operations.pyi +3 -0
  34. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/__init__.pyi +0 -0
  35. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/base.pyi +14 -0
  36. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/creation.pyi +3 -0
  37. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/introspection.pyi +13 -0
  38. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/autodetector.pyi +67 -0
  39. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/executor.pyi +40 -0
  40. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/loader.pyi +31 -0
  41. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/__init__.pyi +22 -0
  42. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/base.pyi +17 -0
  43. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/fields.pyi +32 -0
  44. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/models.pyi +87 -0
  45. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/special.pyi +43 -0
  46. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/utils.pyi +5 -0
  47. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/optimizer.pyi +7 -0
  48. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/state.pyi +68 -0
  49. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/forms/__init__.pyi +86 -0
  50. material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/forms/boundfield.pyi +60 -0
.gitattributes CHANGED
@@ -495,3 +495,4 @@ material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pillow.libs/
495
  material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected_4Classes/1908264_cm.tif filter=lfs diff=lfs merge=lfs -text
496
  material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-55eab65a.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
497
  material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908304_m.tif filter=lfs diff=lfs merge=lfs -text
 
 
495
  material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected_4Classes/1908264_cm.tif filter=lfs diff=lfs merge=lfs -text
496
  material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-55eab65a.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
497
  material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908304_m.tif filter=lfs diff=lfs merge=lfs -text
498
+ material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected_4Classes/1908276_cm.tif filter=lfs diff=lfs merge=lfs -text
material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected_4Classes/1908276_cm.tif ADDED

Git LFS Details

  • SHA256: 1811b9f4b98ac8ec987c685db4e8216f14d1dd09f3273479d0de8e84aed90c1c
  • Pointer size: 132 Bytes
  • Size of remote file: 2.16 MB
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__init__.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .__version__ import __description__, __title__, __version__
2
+ from ._api import *
3
+ from ._auth import *
4
+ from ._client import *
5
+ from ._config import *
6
+ from ._content import *
7
+ from ._exceptions import *
8
+ from ._models import *
9
+ from ._status_codes import *
10
+ from ._transports import *
11
+ from ._types import *
12
+ from ._urls import *
13
+
14
+ try:
15
+ from ._main import main
16
+ except ImportError: # pragma: no cover
17
+
18
+ def main() -> None: # type: ignore
19
+ import sys
20
+
21
+ print(
22
+ "The httpx command line client could not run because the required "
23
+ "dependencies were not installed.\nMake sure you've installed "
24
+ "everything with: pip install 'httpx[cli]'"
25
+ )
26
+ sys.exit(1)
27
+
28
+
29
+ __all__ = [
30
+ "__description__",
31
+ "__title__",
32
+ "__version__",
33
+ "ASGITransport",
34
+ "AsyncBaseTransport",
35
+ "AsyncByteStream",
36
+ "AsyncClient",
37
+ "AsyncHTTPTransport",
38
+ "Auth",
39
+ "BaseTransport",
40
+ "BasicAuth",
41
+ "ByteStream",
42
+ "Client",
43
+ "CloseError",
44
+ "codes",
45
+ "ConnectError",
46
+ "ConnectTimeout",
47
+ "CookieConflict",
48
+ "Cookies",
49
+ "create_ssl_context",
50
+ "DecodingError",
51
+ "delete",
52
+ "DigestAuth",
53
+ "get",
54
+ "head",
55
+ "Headers",
56
+ "HTTPError",
57
+ "HTTPStatusError",
58
+ "HTTPTransport",
59
+ "InvalidURL",
60
+ "Limits",
61
+ "LocalProtocolError",
62
+ "main",
63
+ "MockTransport",
64
+ "NetRCAuth",
65
+ "NetworkError",
66
+ "options",
67
+ "patch",
68
+ "PoolTimeout",
69
+ "post",
70
+ "ProtocolError",
71
+ "Proxy",
72
+ "ProxyError",
73
+ "put",
74
+ "QueryParams",
75
+ "ReadError",
76
+ "ReadTimeout",
77
+ "RemoteProtocolError",
78
+ "request",
79
+ "Request",
80
+ "RequestError",
81
+ "RequestNotRead",
82
+ "Response",
83
+ "ResponseNotRead",
84
+ "stream",
85
+ "StreamClosed",
86
+ "StreamConsumed",
87
+ "StreamError",
88
+ "SyncByteStream",
89
+ "Timeout",
90
+ "TimeoutException",
91
+ "TooManyRedirects",
92
+ "TransportError",
93
+ "UnsupportedProtocol",
94
+ "URL",
95
+ "USE_CLIENT_DEFAULT",
96
+ "WriteError",
97
+ "WriteTimeout",
98
+ "WSGITransport",
99
+ ]
100
+
101
+
102
+ __locals = locals()
103
+ for __name in __all__:
104
+ if not __name.startswith("__"):
105
+ setattr(__locals[__name], "__module__", "httpx") # noqa
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/__version__.cpython-310.pyc ADDED
Binary file (346 Bytes). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_auth.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_decoders.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (6.77 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_auth.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import time
7
+ import typing
8
+ from base64 import b64encode
9
+ from urllib.request import parse_http_list
10
+
11
+ from ._exceptions import ProtocolError
12
+ from ._models import Cookies, Request, Response
13
+ from ._utils import to_bytes, to_str, unquote
14
+
15
+ if typing.TYPE_CHECKING: # pragma: no cover
16
+ from hashlib import _Hash
17
+
18
+
19
+ __all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"]
20
+
21
+
22
+ class Auth:
23
+ """
24
+ Base class for all authentication schemes.
25
+
26
+ To implement a custom authentication scheme, subclass `Auth` and override
27
+ the `.auth_flow()` method.
28
+
29
+ If the authentication scheme does I/O such as disk access or network calls, or uses
30
+ synchronization primitives such as locks, you should override `.sync_auth_flow()`
31
+ and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized
32
+ implementations that will be used by `Client` and `AsyncClient` respectively.
33
+ """
34
+
35
+ requires_request_body = False
36
+ requires_response_body = False
37
+
38
+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
39
+ """
40
+ Execute the authentication flow.
41
+
42
+ To dispatch a request, `yield` it:
43
+
44
+ ```
45
+ yield request
46
+ ```
47
+
48
+ The client will `.send()` the response back into the flow generator. You can
49
+ access it like so:
50
+
51
+ ```
52
+ response = yield request
53
+ ```
54
+
55
+ A `return` (or reaching the end of the generator) will result in the
56
+ client returning the last response obtained from the server.
57
+
58
+ You can dispatch as many requests as is necessary.
59
+ """
60
+ yield request
61
+
62
+ def sync_auth_flow(
63
+ self, request: Request
64
+ ) -> typing.Generator[Request, Response, None]:
65
+ """
66
+ Execute the authentication flow synchronously.
67
+
68
+ By default, this defers to `.auth_flow()`. You should override this method
69
+ when the authentication scheme does I/O and/or uses concurrency primitives.
70
+ """
71
+ if self.requires_request_body:
72
+ request.read()
73
+
74
+ flow = self.auth_flow(request)
75
+ request = next(flow)
76
+
77
+ while True:
78
+ response = yield request
79
+ if self.requires_response_body:
80
+ response.read()
81
+
82
+ try:
83
+ request = flow.send(response)
84
+ except StopIteration:
85
+ break
86
+
87
+ async def async_auth_flow(
88
+ self, request: Request
89
+ ) -> typing.AsyncGenerator[Request, Response]:
90
+ """
91
+ Execute the authentication flow asynchronously.
92
+
93
+ By default, this defers to `.auth_flow()`. You should override this method
94
+ when the authentication scheme does I/O and/or uses concurrency primitives.
95
+ """
96
+ if self.requires_request_body:
97
+ await request.aread()
98
+
99
+ flow = self.auth_flow(request)
100
+ request = next(flow)
101
+
102
+ while True:
103
+ response = yield request
104
+ if self.requires_response_body:
105
+ await response.aread()
106
+
107
+ try:
108
+ request = flow.send(response)
109
+ except StopIteration:
110
+ break
111
+
112
+
113
+ class FunctionAuth(Auth):
114
+ """
115
+ Allows the 'auth' argument to be passed as a simple callable function,
116
+ that takes the request, and returns a new, modified request.
117
+ """
118
+
119
+ def __init__(self, func: typing.Callable[[Request], Request]) -> None:
120
+ self._func = func
121
+
122
+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
123
+ yield self._func(request)
124
+
125
+
126
+ class BasicAuth(Auth):
127
+ """
128
+ Allows the 'auth' argument to be passed as a (username, password) pair,
129
+ and uses HTTP Basic authentication.
130
+ """
131
+
132
+ def __init__(self, username: str | bytes, password: str | bytes) -> None:
133
+ self._auth_header = self._build_auth_header(username, password)
134
+
135
+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
136
+ request.headers["Authorization"] = self._auth_header
137
+ yield request
138
+
139
+ def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
140
+ userpass = b":".join((to_bytes(username), to_bytes(password)))
141
+ token = b64encode(userpass).decode()
142
+ return f"Basic {token}"
143
+
144
+
145
+ class NetRCAuth(Auth):
146
+ """
147
+ Use a 'netrc' file to lookup basic auth credentials based on the url host.
148
+ """
149
+
150
+ def __init__(self, file: str | None = None) -> None:
151
+ # Lazily import 'netrc'.
152
+ # There's no need for us to load this module unless 'NetRCAuth' is being used.
153
+ import netrc
154
+
155
+ self._netrc_info = netrc.netrc(file)
156
+
157
+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
158
+ auth_info = self._netrc_info.authenticators(request.url.host)
159
+ if auth_info is None or not auth_info[2]:
160
+ # The netrc file did not have authentication credentials for this host.
161
+ yield request
162
+ else:
163
+ # Build a basic auth header with credentials from the netrc file.
164
+ request.headers["Authorization"] = self._build_auth_header(
165
+ username=auth_info[0], password=auth_info[2]
166
+ )
167
+ yield request
168
+
169
+ def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
170
+ userpass = b":".join((to_bytes(username), to_bytes(password)))
171
+ token = b64encode(userpass).decode()
172
+ return f"Basic {token}"
173
+
174
+
175
+ class DigestAuth(Auth):
176
+ _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {
177
+ "MD5": hashlib.md5,
178
+ "MD5-SESS": hashlib.md5,
179
+ "SHA": hashlib.sha1,
180
+ "SHA-SESS": hashlib.sha1,
181
+ "SHA-256": hashlib.sha256,
182
+ "SHA-256-SESS": hashlib.sha256,
183
+ "SHA-512": hashlib.sha512,
184
+ "SHA-512-SESS": hashlib.sha512,
185
+ }
186
+
187
+ def __init__(self, username: str | bytes, password: str | bytes) -> None:
188
+ self._username = to_bytes(username)
189
+ self._password = to_bytes(password)
190
+ self._last_challenge: _DigestAuthChallenge | None = None
191
+ self._nonce_count = 1
192
+
193
+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
194
+ if self._last_challenge:
195
+ request.headers["Authorization"] = self._build_auth_header(
196
+ request, self._last_challenge
197
+ )
198
+
199
+ response = yield request
200
+
201
+ if response.status_code != 401 or "www-authenticate" not in response.headers:
202
+ # If the response is not a 401 then we don't
203
+ # need to build an authenticated request.
204
+ return
205
+
206
+ for auth_header in response.headers.get_list("www-authenticate"):
207
+ if auth_header.lower().startswith("digest "):
208
+ break
209
+ else:
210
+ # If the response does not include a 'WWW-Authenticate: Digest ...'
211
+ # header, then we don't need to build an authenticated request.
212
+ return
213
+
214
+ self._last_challenge = self._parse_challenge(request, response, auth_header)
215
+ self._nonce_count = 1
216
+
217
+ request.headers["Authorization"] = self._build_auth_header(
218
+ request, self._last_challenge
219
+ )
220
+ if response.cookies:
221
+ Cookies(response.cookies).set_cookie_header(request=request)
222
+ yield request
223
+
224
+ def _parse_challenge(
225
+ self, request: Request, response: Response, auth_header: str
226
+ ) -> _DigestAuthChallenge:
227
+ """
228
+ Returns a challenge from a Digest WWW-Authenticate header.
229
+ These take the form of:
230
+ `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`
231
+ """
232
+ scheme, _, fields = auth_header.partition(" ")
233
+
234
+ # This method should only ever have been called with a Digest auth header.
235
+ assert scheme.lower() == "digest"
236
+
237
+ header_dict: dict[str, str] = {}
238
+ for field in parse_http_list(fields):
239
+ key, value = field.strip().split("=", 1)
240
+ header_dict[key] = unquote(value)
241
+
242
+ try:
243
+ realm = header_dict["realm"].encode()
244
+ nonce = header_dict["nonce"].encode()
245
+ algorithm = header_dict.get("algorithm", "MD5")
246
+ opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None
247
+ qop = header_dict["qop"].encode() if "qop" in header_dict else None
248
+ return _DigestAuthChallenge(
249
+ realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop
250
+ )
251
+ except KeyError as exc:
252
+ message = "Malformed Digest WWW-Authenticate header"
253
+ raise ProtocolError(message, request=request) from exc
254
+
255
+ def _build_auth_header(
256
+ self, request: Request, challenge: _DigestAuthChallenge
257
+ ) -> str:
258
+ hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]
259
+
260
+ def digest(data: bytes) -> bytes:
261
+ return hash_func(data).hexdigest().encode()
262
+
263
+ A1 = b":".join((self._username, challenge.realm, self._password))
264
+
265
+ path = request.url.raw_path
266
+ A2 = b":".join((request.method.encode(), path))
267
+ # TODO: implement auth-int
268
+ HA2 = digest(A2)
269
+
270
+ nc_value = b"%08x" % self._nonce_count
271
+ cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)
272
+ self._nonce_count += 1
273
+
274
+ HA1 = digest(A1)
275
+ if challenge.algorithm.lower().endswith("-sess"):
276
+ HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
277
+
278
+ qop = self._resolve_qop(challenge.qop, request=request)
279
+ if qop is None:
280
+ # Following RFC 2069
281
+ digest_data = [HA1, challenge.nonce, HA2]
282
+ else:
283
+ # Following RFC 2617/7616
284
+ digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]
285
+
286
+ format_args = {
287
+ "username": self._username,
288
+ "realm": challenge.realm,
289
+ "nonce": challenge.nonce,
290
+ "uri": path,
291
+ "response": digest(b":".join(digest_data)),
292
+ "algorithm": challenge.algorithm.encode(),
293
+ }
294
+ if challenge.opaque:
295
+ format_args["opaque"] = challenge.opaque
296
+ if qop:
297
+ format_args["qop"] = b"auth"
298
+ format_args["nc"] = nc_value
299
+ format_args["cnonce"] = cnonce
300
+
301
+ return "Digest " + self._get_header_value(format_args)
302
+
303
+ def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:
304
+ s = str(nonce_count).encode()
305
+ s += nonce
306
+ s += time.ctime().encode()
307
+ s += os.urandom(8)
308
+
309
+ return hashlib.sha1(s).hexdigest()[:16].encode()
310
+
311
+ def _get_header_value(self, header_fields: dict[str, bytes]) -> str:
312
+ NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")
313
+ QUOTED_TEMPLATE = '{}="{}"'
314
+ NON_QUOTED_TEMPLATE = "{}={}"
315
+
316
+ header_value = ""
317
+ for i, (field, value) in enumerate(header_fields.items()):
318
+ if i > 0:
319
+ header_value += ", "
320
+ template = (
321
+ QUOTED_TEMPLATE
322
+ if field not in NON_QUOTED_FIELDS
323
+ else NON_QUOTED_TEMPLATE
324
+ )
325
+ header_value += template.format(field, to_str(value))
326
+
327
+ return header_value
328
+
329
+ def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None:
330
+ if qop is None:
331
+ return None
332
+ qops = re.split(b", ?", qop)
333
+ if b"auth" in qops:
334
+ return b"auth"
335
+
336
+ if qops == [b"auth-int"]:
337
+ raise NotImplementedError("Digest auth-int support is not yet implemented")
338
+
339
+ message = f'Unexpected qop value "{qop!r}" in digest auth'
340
+ raise ProtocolError(message, request=request)
341
+
342
+
343
+ class _DigestAuthChallenge(typing.NamedTuple):
344
+ realm: bytes
345
+ nonce: bytes
346
+ algorithm: str
347
+ opaque: bytes | None
348
+ qop: bytes | None
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_client.py ADDED
@@ -0,0 +1,2019 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import enum
5
+ import logging
6
+ import time
7
+ import typing
8
+ import warnings
9
+ from contextlib import asynccontextmanager, contextmanager
10
+ from types import TracebackType
11
+
12
+ from .__version__ import __version__
13
+ from ._auth import Auth, BasicAuth, FunctionAuth
14
+ from ._config import (
15
+ DEFAULT_LIMITS,
16
+ DEFAULT_MAX_REDIRECTS,
17
+ DEFAULT_TIMEOUT_CONFIG,
18
+ Limits,
19
+ Proxy,
20
+ Timeout,
21
+ )
22
+ from ._decoders import SUPPORTED_DECODERS
23
+ from ._exceptions import (
24
+ InvalidURL,
25
+ RemoteProtocolError,
26
+ TooManyRedirects,
27
+ request_context,
28
+ )
29
+ from ._models import Cookies, Headers, Request, Response
30
+ from ._status_codes import codes
31
+ from ._transports.base import AsyncBaseTransport, BaseTransport
32
+ from ._transports.default import AsyncHTTPTransport, HTTPTransport
33
+ from ._types import (
34
+ AsyncByteStream,
35
+ AuthTypes,
36
+ CertTypes,
37
+ CookieTypes,
38
+ HeaderTypes,
39
+ ProxyTypes,
40
+ QueryParamTypes,
41
+ RequestContent,
42
+ RequestData,
43
+ RequestExtensions,
44
+ RequestFiles,
45
+ SyncByteStream,
46
+ TimeoutTypes,
47
+ )
48
+ from ._urls import URL, QueryParams
49
+ from ._utils import URLPattern, get_environment_proxies
50
+
51
+ if typing.TYPE_CHECKING:
52
+ import ssl # pragma: no cover
53
+
54
+ __all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]
55
+
56
+ # The type annotation for @classmethod and context managers here follows PEP 484
57
+ # https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods
58
+ T = typing.TypeVar("T", bound="Client")
59
+ U = typing.TypeVar("U", bound="AsyncClient")
60
+
61
+
62
+ def _is_https_redirect(url: URL, location: URL) -> bool:
63
+ """
64
+ Return 'True' if 'location' is a HTTPS upgrade of 'url'
65
+ """
66
+ if url.host != location.host:
67
+ return False
68
+
69
+ return (
70
+ url.scheme == "http"
71
+ and _port_or_default(url) == 80
72
+ and location.scheme == "https"
73
+ and _port_or_default(location) == 443
74
+ )
75
+
76
+
77
+ def _port_or_default(url: URL) -> int | None:
78
+ if url.port is not None:
79
+ return url.port
80
+ return {"http": 80, "https": 443}.get(url.scheme)
81
+
82
+
83
+ def _same_origin(url: URL, other: URL) -> bool:
84
+ """
85
+ Return 'True' if the given URLs share the same origin.
86
+ """
87
+ return (
88
+ url.scheme == other.scheme
89
+ and url.host == other.host
90
+ and _port_or_default(url) == _port_or_default(other)
91
+ )
92
+
93
+
94
+ class UseClientDefault:
95
+ """
96
+ For some parameters such as `auth=...` and `timeout=...` we need to be able
97
+ to indicate the default "unset" state, in a way that is distinctly different
98
+ to using `None`.
99
+
100
+ The default "unset" state indicates that whatever default is set on the
101
+ client should be used. This is different to setting `None`, which
102
+ explicitly disables the parameter, possibly overriding a client default.
103
+
104
+ For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature.
105
+ Omitting the `timeout` parameter will send a request using whatever default
106
+ timeout has been configured on the client. Including `timeout=None` will
107
+ ensure no timeout is used.
108
+
109
+ Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant,
110
+ but it is used internally when a parameter is not included.
111
+ """
112
+
113
+
114
+ USE_CLIENT_DEFAULT = UseClientDefault()
115
+
116
+
117
+ logger = logging.getLogger("httpx")
118
+
119
+ USER_AGENT = f"python-httpx/{__version__}"
120
+ ACCEPT_ENCODING = ", ".join(
121
+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]
122
+ )
123
+
124
+
125
+ class ClientState(enum.Enum):
126
+ # UNOPENED:
127
+ # The client has been instantiated, but has not been used to send a request,
128
+ # or been opened by entering the context of a `with` block.
129
+ UNOPENED = 1
130
+ # OPENED:
131
+ # The client has either sent a request, or is within a `with` block.
132
+ OPENED = 2
133
+ # CLOSED:
134
+ # The client has either exited the `with` block, or `close()` has
135
+ # been called explicitly.
136
+ CLOSED = 3
137
+
138
+
139
+ class BoundSyncStream(SyncByteStream):
140
+ """
141
+ A byte stream that is bound to a given response instance, and that
142
+ ensures the `response.elapsed` is set once the response is closed.
143
+ """
144
+
145
+ def __init__(
146
+ self, stream: SyncByteStream, response: Response, start: float
147
+ ) -> None:
148
+ self._stream = stream
149
+ self._response = response
150
+ self._start = start
151
+
152
+ def __iter__(self) -> typing.Iterator[bytes]:
153
+ for chunk in self._stream:
154
+ yield chunk
155
+
156
+ def close(self) -> None:
157
+ elapsed = time.perf_counter() - self._start
158
+ self._response.elapsed = datetime.timedelta(seconds=elapsed)
159
+ self._stream.close()
160
+
161
+
162
+ class BoundAsyncStream(AsyncByteStream):
163
+ """
164
+ An async byte stream that is bound to a given response instance, and that
165
+ ensures the `response.elapsed` is set once the response is closed.
166
+ """
167
+
168
+ def __init__(
169
+ self, stream: AsyncByteStream, response: Response, start: float
170
+ ) -> None:
171
+ self._stream = stream
172
+ self._response = response
173
+ self._start = start
174
+
175
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
176
+ async for chunk in self._stream:
177
+ yield chunk
178
+
179
+ async def aclose(self) -> None:
180
+ elapsed = time.perf_counter() - self._start
181
+ self._response.elapsed = datetime.timedelta(seconds=elapsed)
182
+ await self._stream.aclose()
183
+
184
+
185
+ EventHook = typing.Callable[..., typing.Any]
186
+
187
+
188
+ class BaseClient:
189
+ def __init__(
190
+ self,
191
+ *,
192
+ auth: AuthTypes | None = None,
193
+ params: QueryParamTypes | None = None,
194
+ headers: HeaderTypes | None = None,
195
+ cookies: CookieTypes | None = None,
196
+ timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
197
+ follow_redirects: bool = False,
198
+ max_redirects: int = DEFAULT_MAX_REDIRECTS,
199
+ event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
200
+ base_url: URL | str = "",
201
+ trust_env: bool = True,
202
+ default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
203
+ ) -> None:
204
+ event_hooks = {} if event_hooks is None else event_hooks
205
+
206
+ self._base_url = self._enforce_trailing_slash(URL(base_url))
207
+
208
+ self._auth = self._build_auth(auth)
209
+ self._params = QueryParams(params)
210
+ self.headers = Headers(headers)
211
+ self._cookies = Cookies(cookies)
212
+ self._timeout = Timeout(timeout)
213
+ self.follow_redirects = follow_redirects
214
+ self.max_redirects = max_redirects
215
+ self._event_hooks = {
216
+ "request": list(event_hooks.get("request", [])),
217
+ "response": list(event_hooks.get("response", [])),
218
+ }
219
+ self._trust_env = trust_env
220
+ self._default_encoding = default_encoding
221
+ self._state = ClientState.UNOPENED
222
+
223
+ @property
224
+ def is_closed(self) -> bool:
225
+ """
226
+ Check if the client being closed
227
+ """
228
+ return self._state == ClientState.CLOSED
229
+
230
+ @property
231
+ def trust_env(self) -> bool:
232
+ return self._trust_env
233
+
234
+ def _enforce_trailing_slash(self, url: URL) -> URL:
235
+ if url.raw_path.endswith(b"/"):
236
+ return url
237
+ return url.copy_with(raw_path=url.raw_path + b"/")
238
+
239
+ def _get_proxy_map(
240
+ self, proxy: ProxyTypes | None, allow_env_proxies: bool
241
+ ) -> dict[str, Proxy | None]:
242
+ if proxy is None:
243
+ if allow_env_proxies:
244
+ return {
245
+ key: None if url is None else Proxy(url=url)
246
+ for key, url in get_environment_proxies().items()
247
+ }
248
+ return {}
249
+ else:
250
+ proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
251
+ return {"all://": proxy}
252
+
253
+ @property
254
+ def timeout(self) -> Timeout:
255
+ return self._timeout
256
+
257
+ @timeout.setter
258
+ def timeout(self, timeout: TimeoutTypes) -> None:
259
+ self._timeout = Timeout(timeout)
260
+
261
+ @property
262
+ def event_hooks(self) -> dict[str, list[EventHook]]:
263
+ return self._event_hooks
264
+
265
+ @event_hooks.setter
266
+ def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None:
267
+ self._event_hooks = {
268
+ "request": list(event_hooks.get("request", [])),
269
+ "response": list(event_hooks.get("response", [])),
270
+ }
271
+
272
+ @property
273
+ def auth(self) -> Auth | None:
274
+ """
275
+ Authentication class used when none is passed at the request-level.
276
+
277
+ See also [Authentication][0].
278
+
279
+ [0]: /quickstart/#authentication
280
+ """
281
+ return self._auth
282
+
283
+ @auth.setter
284
+ def auth(self, auth: AuthTypes) -> None:
285
+ self._auth = self._build_auth(auth)
286
+
287
+ @property
288
+ def base_url(self) -> URL:
289
+ """
290
+ Base URL to use when sending requests with relative URLs.
291
+ """
292
+ return self._base_url
293
+
294
+ @base_url.setter
295
+ def base_url(self, url: URL | str) -> None:
296
+ self._base_url = self._enforce_trailing_slash(URL(url))
297
+
298
+ @property
299
+ def headers(self) -> Headers:
300
+ """
301
+ HTTP headers to include when sending requests.
302
+ """
303
+ return self._headers
304
+
305
+ @headers.setter
306
+ def headers(self, headers: HeaderTypes) -> None:
307
+ client_headers = Headers(
308
+ {
309
+ b"Accept": b"*/*",
310
+ b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"),
311
+ b"Connection": b"keep-alive",
312
+ b"User-Agent": USER_AGENT.encode("ascii"),
313
+ }
314
+ )
315
+ client_headers.update(headers)
316
+ self._headers = client_headers
317
+
318
+ @property
319
+ def cookies(self) -> Cookies:
320
+ """
321
+ Cookie values to include when sending requests.
322
+ """
323
+ return self._cookies
324
+
325
+ @cookies.setter
326
+ def cookies(self, cookies: CookieTypes) -> None:
327
+ self._cookies = Cookies(cookies)
328
+
329
+ @property
330
+ def params(self) -> QueryParams:
331
+ """
332
+ Query parameters to include in the URL when sending requests.
333
+ """
334
+ return self._params
335
+
336
+ @params.setter
337
+ def params(self, params: QueryParamTypes) -> None:
338
+ self._params = QueryParams(params)
339
+
340
+ def build_request(
341
+ self,
342
+ method: str,
343
+ url: URL | str,
344
+ *,
345
+ content: RequestContent | None = None,
346
+ data: RequestData | None = None,
347
+ files: RequestFiles | None = None,
348
+ json: typing.Any | None = None,
349
+ params: QueryParamTypes | None = None,
350
+ headers: HeaderTypes | None = None,
351
+ cookies: CookieTypes | None = None,
352
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
353
+ extensions: RequestExtensions | None = None,
354
+ ) -> Request:
355
+ """
356
+ Build and return a request instance.
357
+
358
+ * The `params`, `headers` and `cookies` arguments
359
+ are merged with any values set on the client.
360
+ * The `url` argument is merged with any `base_url` set on the client.
361
+
362
+ See also: [Request instances][0]
363
+
364
+ [0]: /advanced/clients/#request-instances
365
+ """
366
+ url = self._merge_url(url)
367
+ headers = self._merge_headers(headers)
368
+ cookies = self._merge_cookies(cookies)
369
+ params = self._merge_queryparams(params)
370
+ extensions = {} if extensions is None else extensions
371
+ if "timeout" not in extensions:
372
+ timeout = (
373
+ self.timeout
374
+ if isinstance(timeout, UseClientDefault)
375
+ else Timeout(timeout)
376
+ )
377
+ extensions = dict(**extensions, timeout=timeout.as_dict())
378
+ return Request(
379
+ method,
380
+ url,
381
+ content=content,
382
+ data=data,
383
+ files=files,
384
+ json=json,
385
+ params=params,
386
+ headers=headers,
387
+ cookies=cookies,
388
+ extensions=extensions,
389
+ )
390
+
391
+ def _merge_url(self, url: URL | str) -> URL:
392
+ """
393
+ Merge a URL argument together with any 'base_url' on the client,
394
+ to create the URL used for the outgoing request.
395
+ """
396
+ merge_url = URL(url)
397
+ if merge_url.is_relative_url:
398
+ # To merge URLs we always append to the base URL. To get this
399
+ # behaviour correct we always ensure the base URL ends in a '/'
400
+ # separator, and strip any leading '/' from the merge URL.
401
+ #
402
+ # So, eg...
403
+ #
404
+ # >>> client = Client(base_url="https://www.example.com/subpath")
405
+ # >>> client.base_url
406
+ # URL('https://www.example.com/subpath/')
407
+ # >>> client.build_request("GET", "/path").url
408
+ # URL('https://www.example.com/subpath/path')
409
+ merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
410
+ return self.base_url.copy_with(raw_path=merge_raw_path)
411
+ return merge_url
412
+
413
+ def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None:
414
+ """
415
+ Merge a cookies argument together with any cookies on the client,
416
+ to create the cookies used for the outgoing request.
417
+ """
418
+ if cookies or self.cookies:
419
+ merged_cookies = Cookies(self.cookies)
420
+ merged_cookies.update(cookies)
421
+ return merged_cookies
422
+ return cookies
423
+
424
+ def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None:
425
+ """
426
+ Merge a headers argument together with any headers on the client,
427
+ to create the headers used for the outgoing request.
428
+ """
429
+ merged_headers = Headers(self.headers)
430
+ merged_headers.update(headers)
431
+ return merged_headers
432
+
433
+ def _merge_queryparams(
434
+ self, params: QueryParamTypes | None = None
435
+ ) -> QueryParamTypes | None:
436
+ """
437
+ Merge a queryparams argument together with any queryparams on the client,
438
+ to create the queryparams used for the outgoing request.
439
+ """
440
+ if params or self.params:
441
+ merged_queryparams = QueryParams(self.params)
442
+ return merged_queryparams.merge(params)
443
+ return params
444
+
445
+ def _build_auth(self, auth: AuthTypes | None) -> Auth | None:
446
+ if auth is None:
447
+ return None
448
+ elif isinstance(auth, tuple):
449
+ return BasicAuth(username=auth[0], password=auth[1])
450
+ elif isinstance(auth, Auth):
451
+ return auth
452
+ elif callable(auth):
453
+ return FunctionAuth(func=auth)
454
+ else:
455
+ raise TypeError(f'Invalid "auth" argument: {auth!r}')
456
+
457
+ def _build_request_auth(
458
+ self,
459
+ request: Request,
460
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
461
+ ) -> Auth:
462
+ auth = (
463
+ self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth)
464
+ )
465
+
466
+ if auth is not None:
467
+ return auth
468
+
469
+ username, password = request.url.username, request.url.password
470
+ if username or password:
471
+ return BasicAuth(username=username, password=password)
472
+
473
+ return Auth()
474
+
475
+ def _build_redirect_request(self, request: Request, response: Response) -> Request:
476
+ """
477
+ Given a request and a redirect response, return a new request that
478
+ should be used to effect the redirect.
479
+ """
480
+ method = self._redirect_method(request, response)
481
+ url = self._redirect_url(request, response)
482
+ headers = self._redirect_headers(request, url, method)
483
+ stream = self._redirect_stream(request, method)
484
+ cookies = Cookies(self.cookies)
485
+ return Request(
486
+ method=method,
487
+ url=url,
488
+ headers=headers,
489
+ cookies=cookies,
490
+ stream=stream,
491
+ extensions=request.extensions,
492
+ )
493
+
494
+ def _redirect_method(self, request: Request, response: Response) -> str:
495
+ """
496
+ When being redirected we may want to change the method of the request
497
+ based on certain specs or browser behavior.
498
+ """
499
+ method = request.method
500
+
501
+ # https://tools.ietf.org/html/rfc7231#section-6.4.4
502
+ if response.status_code == codes.SEE_OTHER and method != "HEAD":
503
+ method = "GET"
504
+
505
+ # Do what the browsers do, despite standards...
506
+ # Turn 302s into GETs.
507
+ if response.status_code == codes.FOUND and method != "HEAD":
508
+ method = "GET"
509
+
510
+ # If a POST is responded to with a 301, turn it into a GET.
511
+ # This bizarre behaviour is explained in 'requests' issue 1704.
512
+ if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":
513
+ method = "GET"
514
+
515
+ return method
516
+
517
+ def _redirect_url(self, request: Request, response: Response) -> URL:
518
+ """
519
+ Return the URL for the redirect to follow.
520
+ """
521
+ location = response.headers["Location"]
522
+
523
+ try:
524
+ url = URL(location)
525
+ except InvalidURL as exc:
526
+ raise RemoteProtocolError(
527
+ f"Invalid URL in location header: {exc}.", request=request
528
+ ) from None
529
+
530
+ # Handle malformed 'Location' headers that are "absolute" form, have no host.
531
+ # See: https://github.com/encode/httpx/issues/771
532
+ if url.scheme and not url.host:
533
+ url = url.copy_with(host=request.url.host)
534
+
535
+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.
536
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
537
+ if url.is_relative_url:
538
+ url = request.url.join(url)
539
+
540
+ # Attach previous fragment if needed (RFC 7231 7.1.2)
541
+ if request.url.fragment and not url.fragment:
542
+ url = url.copy_with(fragment=request.url.fragment)
543
+
544
+ return url
545
+
546
+ def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers:
547
+ """
548
+ Return the headers that should be used for the redirect request.
549
+ """
550
+ headers = Headers(request.headers)
551
+
552
+ if not _same_origin(url, request.url):
553
+ if not _is_https_redirect(request.url, url):
554
+ # Strip Authorization headers when responses are redirected
555
+ # away from the origin. (Except for direct HTTP to HTTPS redirects.)
556
+ headers.pop("Authorization", None)
557
+
558
+ # Update the Host header.
559
+ headers["Host"] = url.netloc.decode("ascii")
560
+
561
+ if method != request.method and method == "GET":
562
+ # If we've switch to a 'GET' request, then strip any headers which
563
+ # are only relevant to the request body.
564
+ headers.pop("Content-Length", None)
565
+ headers.pop("Transfer-Encoding", None)
566
+
567
+ # We should use the client cookie store to determine any cookie header,
568
+ # rather than whatever was on the original outgoing request.
569
+ headers.pop("Cookie", None)
570
+
571
+ return headers
572
+
573
+ def _redirect_stream(
574
+ self, request: Request, method: str
575
+ ) -> SyncByteStream | AsyncByteStream | None:
576
+ """
577
+ Return the body that should be used for the redirect request.
578
+ """
579
+ if method != request.method and method == "GET":
580
+ return None
581
+
582
+ return request.stream
583
+
584
+ def _set_timeout(self, request: Request) -> None:
585
+ if "timeout" not in request.extensions:
586
+ timeout = (
587
+ self.timeout
588
+ if isinstance(self.timeout, UseClientDefault)
589
+ else Timeout(self.timeout)
590
+ )
591
+ request.extensions = dict(**request.extensions, timeout=timeout.as_dict())
592
+
593
+
594
+ class Client(BaseClient):
595
+ """
596
+ An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.
597
+
598
+ It can be shared between threads.
599
+
600
+ Usage:
601
+
602
+ ```python
603
+ >>> client = httpx.Client()
604
+ >>> response = client.get('https://example.org')
605
+ ```
606
+
607
+ **Parameters:**
608
+
609
+ * **auth** - *(optional)* An authentication class to use when sending
610
+ requests.
611
+ * **params** - *(optional)* Query parameters to include in request URLs, as
612
+ a string, dictionary, or sequence of two-tuples.
613
+ * **headers** - *(optional)* Dictionary of HTTP headers to include when
614
+ sending requests.
615
+ * **cookies** - *(optional)* Dictionary of Cookie items to include when
616
+ sending requests.
617
+ * **verify** - *(optional)* Either `True` to use an SSL context with the
618
+ default CA bundle, `False` to disable verification, or an instance of
619
+ `ssl.SSLContext` to use a custom context.
620
+ * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
621
+ enabled. Defaults to `False`.
622
+ * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
623
+ * **timeout** - *(optional)* The timeout configuration to use when sending
624
+ requests.
625
+ * **limits** - *(optional)* The limits configuration to use.
626
+ * **max_redirects** - *(optional)* The maximum number of redirect responses
627
+ that should be followed.
628
+ * **base_url** - *(optional)* A URL to use as the base when building
629
+ request URLs.
630
+ * **transport** - *(optional)* A transport class to use for sending requests
631
+ over the network.
632
+ * **trust_env** - *(optional)* Enables or disables usage of environment
633
+ variables for configuration.
634
+ * **default_encoding** - *(optional)* The default encoding to use for decoding
635
+ response text, if no charset information is included in a response Content-Type
636
+ header. Set to a callable for automatic character set detection. Default: "utf-8".
637
+ """
638
+
639
+ def __init__(
640
+ self,
641
+ *,
642
+ auth: AuthTypes | None = None,
643
+ params: QueryParamTypes | None = None,
644
+ headers: HeaderTypes | None = None,
645
+ cookies: CookieTypes | None = None,
646
+ verify: ssl.SSLContext | str | bool = True,
647
+ cert: CertTypes | None = None,
648
+ trust_env: bool = True,
649
+ http1: bool = True,
650
+ http2: bool = False,
651
+ proxy: ProxyTypes | None = None,
652
+ mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
653
+ timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
654
+ follow_redirects: bool = False,
655
+ limits: Limits = DEFAULT_LIMITS,
656
+ max_redirects: int = DEFAULT_MAX_REDIRECTS,
657
+ event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
658
+ base_url: URL | str = "",
659
+ transport: BaseTransport | None = None,
660
+ default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
661
+ ) -> None:
662
+ super().__init__(
663
+ auth=auth,
664
+ params=params,
665
+ headers=headers,
666
+ cookies=cookies,
667
+ timeout=timeout,
668
+ follow_redirects=follow_redirects,
669
+ max_redirects=max_redirects,
670
+ event_hooks=event_hooks,
671
+ base_url=base_url,
672
+ trust_env=trust_env,
673
+ default_encoding=default_encoding,
674
+ )
675
+
676
+ if http2:
677
+ try:
678
+ import h2 # noqa
679
+ except ImportError: # pragma: no cover
680
+ raise ImportError(
681
+ "Using http2=True, but the 'h2' package is not installed. "
682
+ "Make sure to install httpx using `pip install httpx[http2]`."
683
+ ) from None
684
+
685
+ allow_env_proxies = trust_env and transport is None
686
+ proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
687
+
688
+ self._transport = self._init_transport(
689
+ verify=verify,
690
+ cert=cert,
691
+ trust_env=trust_env,
692
+ http1=http1,
693
+ http2=http2,
694
+ limits=limits,
695
+ transport=transport,
696
+ )
697
+ self._mounts: dict[URLPattern, BaseTransport | None] = {
698
+ URLPattern(key): None
699
+ if proxy is None
700
+ else self._init_proxy_transport(
701
+ proxy,
702
+ verify=verify,
703
+ cert=cert,
704
+ trust_env=trust_env,
705
+ http1=http1,
706
+ http2=http2,
707
+ limits=limits,
708
+ )
709
+ for key, proxy in proxy_map.items()
710
+ }
711
+ if mounts is not None:
712
+ self._mounts.update(
713
+ {URLPattern(key): transport for key, transport in mounts.items()}
714
+ )
715
+
716
+ self._mounts = dict(sorted(self._mounts.items()))
717
+
718
+ def _init_transport(
719
+ self,
720
+ verify: ssl.SSLContext | str | bool = True,
721
+ cert: CertTypes | None = None,
722
+ trust_env: bool = True,
723
+ http1: bool = True,
724
+ http2: bool = False,
725
+ limits: Limits = DEFAULT_LIMITS,
726
+ transport: BaseTransport | None = None,
727
+ ) -> BaseTransport:
728
+ if transport is not None:
729
+ return transport
730
+
731
+ return HTTPTransport(
732
+ verify=verify,
733
+ cert=cert,
734
+ trust_env=trust_env,
735
+ http1=http1,
736
+ http2=http2,
737
+ limits=limits,
738
+ )
739
+
740
+ def _init_proxy_transport(
741
+ self,
742
+ proxy: Proxy,
743
+ verify: ssl.SSLContext | str | bool = True,
744
+ cert: CertTypes | None = None,
745
+ trust_env: bool = True,
746
+ http1: bool = True,
747
+ http2: bool = False,
748
+ limits: Limits = DEFAULT_LIMITS,
749
+ ) -> BaseTransport:
750
+ return HTTPTransport(
751
+ verify=verify,
752
+ cert=cert,
753
+ trust_env=trust_env,
754
+ http1=http1,
755
+ http2=http2,
756
+ limits=limits,
757
+ proxy=proxy,
758
+ )
759
+
760
+ def _transport_for_url(self, url: URL) -> BaseTransport:
761
+ """
762
+ Returns the transport instance that should be used for a given URL.
763
+ This will either be the standard connection pool, or a proxy.
764
+ """
765
+ for pattern, transport in self._mounts.items():
766
+ if pattern.matches(url):
767
+ return self._transport if transport is None else transport
768
+
769
+ return self._transport
770
+
771
+ def request(
772
+ self,
773
+ method: str,
774
+ url: URL | str,
775
+ *,
776
+ content: RequestContent | None = None,
777
+ data: RequestData | None = None,
778
+ files: RequestFiles | None = None,
779
+ json: typing.Any | None = None,
780
+ params: QueryParamTypes | None = None,
781
+ headers: HeaderTypes | None = None,
782
+ cookies: CookieTypes | None = None,
783
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
784
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
785
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
786
+ extensions: RequestExtensions | None = None,
787
+ ) -> Response:
788
+ """
789
+ Build and send a request.
790
+
791
+ Equivalent to:
792
+
793
+ ```python
794
+ request = client.build_request(...)
795
+ response = client.send(request, ...)
796
+ ```
797
+
798
+ See `Client.build_request()`, `Client.send()` and
799
+ [Merging of configuration][0] for how the various parameters
800
+ are merged with client-level configuration.
801
+
802
+ [0]: /advanced/clients/#merging-of-configuration
803
+ """
804
+ if cookies is not None:
805
+ message = (
806
+ "Setting per-request cookies=<...> is being deprecated, because "
807
+ "the expected behaviour on cookie persistence is ambiguous. Set "
808
+ "cookies directly on the client instance instead."
809
+ )
810
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
811
+
812
+ request = self.build_request(
813
+ method=method,
814
+ url=url,
815
+ content=content,
816
+ data=data,
817
+ files=files,
818
+ json=json,
819
+ params=params,
820
+ headers=headers,
821
+ cookies=cookies,
822
+ timeout=timeout,
823
+ extensions=extensions,
824
+ )
825
+ return self.send(request, auth=auth, follow_redirects=follow_redirects)
826
+
827
+ @contextmanager
828
+ def stream(
829
+ self,
830
+ method: str,
831
+ url: URL | str,
832
+ *,
833
+ content: RequestContent | None = None,
834
+ data: RequestData | None = None,
835
+ files: RequestFiles | None = None,
836
+ json: typing.Any | None = None,
837
+ params: QueryParamTypes | None = None,
838
+ headers: HeaderTypes | None = None,
839
+ cookies: CookieTypes | None = None,
840
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
841
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
842
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
843
+ extensions: RequestExtensions | None = None,
844
+ ) -> typing.Iterator[Response]:
845
+ """
846
+ Alternative to `httpx.request()` that streams the response body
847
+ instead of loading it into memory at once.
848
+
849
+ **Parameters**: See `httpx.request`.
850
+
851
+ See also: [Streaming Responses][0]
852
+
853
+ [0]: /quickstart#streaming-responses
854
+ """
855
+ request = self.build_request(
856
+ method=method,
857
+ url=url,
858
+ content=content,
859
+ data=data,
860
+ files=files,
861
+ json=json,
862
+ params=params,
863
+ headers=headers,
864
+ cookies=cookies,
865
+ timeout=timeout,
866
+ extensions=extensions,
867
+ )
868
+ response = self.send(
869
+ request=request,
870
+ auth=auth,
871
+ follow_redirects=follow_redirects,
872
+ stream=True,
873
+ )
874
+ try:
875
+ yield response
876
+ finally:
877
+ response.close()
878
+
879
+ def send(
880
+ self,
881
+ request: Request,
882
+ *,
883
+ stream: bool = False,
884
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
885
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
886
+ ) -> Response:
887
+ """
888
+ Send a request.
889
+
890
+ The request is sent as-is, unmodified.
891
+
892
+ Typically you'll want to build one with `Client.build_request()`
893
+ so that any client-level configuration is merged into the request,
894
+ but passing an explicit `httpx.Request()` is supported as well.
895
+
896
+ See also: [Request instances][0]
897
+
898
+ [0]: /advanced/clients/#request-instances
899
+ """
900
+ if self._state == ClientState.CLOSED:
901
+ raise RuntimeError("Cannot send a request, as the client has been closed.")
902
+
903
+ self._state = ClientState.OPENED
904
+ follow_redirects = (
905
+ self.follow_redirects
906
+ if isinstance(follow_redirects, UseClientDefault)
907
+ else follow_redirects
908
+ )
909
+
910
+ self._set_timeout(request)
911
+
912
+ auth = self._build_request_auth(request, auth)
913
+
914
+ response = self._send_handling_auth(
915
+ request,
916
+ auth=auth,
917
+ follow_redirects=follow_redirects,
918
+ history=[],
919
+ )
920
+ try:
921
+ if not stream:
922
+ response.read()
923
+
924
+ return response
925
+
926
+ except BaseException as exc:
927
+ response.close()
928
+ raise exc
929
+
930
+ def _send_handling_auth(
931
+ self,
932
+ request: Request,
933
+ auth: Auth,
934
+ follow_redirects: bool,
935
+ history: list[Response],
936
+ ) -> Response:
937
+ auth_flow = auth.sync_auth_flow(request)
938
+ try:
939
+ request = next(auth_flow)
940
+
941
+ while True:
942
+ response = self._send_handling_redirects(
943
+ request,
944
+ follow_redirects=follow_redirects,
945
+ history=history,
946
+ )
947
+ try:
948
+ try:
949
+ next_request = auth_flow.send(response)
950
+ except StopIteration:
951
+ return response
952
+
953
+ response.history = list(history)
954
+ response.read()
955
+ request = next_request
956
+ history.append(response)
957
+
958
+ except BaseException as exc:
959
+ response.close()
960
+ raise exc
961
+ finally:
962
+ auth_flow.close()
963
+
964
+ def _send_handling_redirects(
965
+ self,
966
+ request: Request,
967
+ follow_redirects: bool,
968
+ history: list[Response],
969
+ ) -> Response:
970
+ while True:
971
+ if len(history) > self.max_redirects:
972
+ raise TooManyRedirects(
973
+ "Exceeded maximum allowed redirects.", request=request
974
+ )
975
+
976
+ for hook in self._event_hooks["request"]:
977
+ hook(request)
978
+
979
+ response = self._send_single_request(request)
980
+ try:
981
+ for hook in self._event_hooks["response"]:
982
+ hook(response)
983
+ response.history = list(history)
984
+
985
+ if not response.has_redirect_location:
986
+ return response
987
+
988
+ request = self._build_redirect_request(request, response)
989
+ history = history + [response]
990
+
991
+ if follow_redirects:
992
+ response.read()
993
+ else:
994
+ response.next_request = request
995
+ return response
996
+
997
+ except BaseException as exc:
998
+ response.close()
999
+ raise exc
1000
+
1001
+ def _send_single_request(self, request: Request) -> Response:
1002
+ """
1003
+ Sends a single request, without handling any redirections.
1004
+ """
1005
+ transport = self._transport_for_url(request.url)
1006
+ start = time.perf_counter()
1007
+
1008
+ if not isinstance(request.stream, SyncByteStream):
1009
+ raise RuntimeError(
1010
+ "Attempted to send an async request with a sync Client instance."
1011
+ )
1012
+
1013
+ with request_context(request=request):
1014
+ response = transport.handle_request(request)
1015
+
1016
+ assert isinstance(response.stream, SyncByteStream)
1017
+
1018
+ response.request = request
1019
+ response.stream = BoundSyncStream(
1020
+ response.stream, response=response, start=start
1021
+ )
1022
+ self.cookies.extract_cookies(response)
1023
+ response.default_encoding = self._default_encoding
1024
+
1025
+ logger.info(
1026
+ 'HTTP Request: %s %s "%s %d %s"',
1027
+ request.method,
1028
+ request.url,
1029
+ response.http_version,
1030
+ response.status_code,
1031
+ response.reason_phrase,
1032
+ )
1033
+
1034
+ return response
1035
+
1036
+ def get(
1037
+ self,
1038
+ url: URL | str,
1039
+ *,
1040
+ params: QueryParamTypes | None = None,
1041
+ headers: HeaderTypes | None = None,
1042
+ cookies: CookieTypes | None = None,
1043
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1044
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1045
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1046
+ extensions: RequestExtensions | None = None,
1047
+ ) -> Response:
1048
+ """
1049
+ Send a `GET` request.
1050
+
1051
+ **Parameters**: See `httpx.request`.
1052
+ """
1053
+ return self.request(
1054
+ "GET",
1055
+ url,
1056
+ params=params,
1057
+ headers=headers,
1058
+ cookies=cookies,
1059
+ auth=auth,
1060
+ follow_redirects=follow_redirects,
1061
+ timeout=timeout,
1062
+ extensions=extensions,
1063
+ )
1064
+
1065
+ def options(
1066
+ self,
1067
+ url: URL | str,
1068
+ *,
1069
+ params: QueryParamTypes | None = None,
1070
+ headers: HeaderTypes | None = None,
1071
+ cookies: CookieTypes | None = None,
1072
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1073
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1074
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1075
+ extensions: RequestExtensions | None = None,
1076
+ ) -> Response:
1077
+ """
1078
+ Send an `OPTIONS` request.
1079
+
1080
+ **Parameters**: See `httpx.request`.
1081
+ """
1082
+ return self.request(
1083
+ "OPTIONS",
1084
+ url,
1085
+ params=params,
1086
+ headers=headers,
1087
+ cookies=cookies,
1088
+ auth=auth,
1089
+ follow_redirects=follow_redirects,
1090
+ timeout=timeout,
1091
+ extensions=extensions,
1092
+ )
1093
+
1094
+ def head(
1095
+ self,
1096
+ url: URL | str,
1097
+ *,
1098
+ params: QueryParamTypes | None = None,
1099
+ headers: HeaderTypes | None = None,
1100
+ cookies: CookieTypes | None = None,
1101
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1102
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1103
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1104
+ extensions: RequestExtensions | None = None,
1105
+ ) -> Response:
1106
+ """
1107
+ Send a `HEAD` request.
1108
+
1109
+ **Parameters**: See `httpx.request`.
1110
+ """
1111
+ return self.request(
1112
+ "HEAD",
1113
+ url,
1114
+ params=params,
1115
+ headers=headers,
1116
+ cookies=cookies,
1117
+ auth=auth,
1118
+ follow_redirects=follow_redirects,
1119
+ timeout=timeout,
1120
+ extensions=extensions,
1121
+ )
1122
+
1123
+ def post(
1124
+ self,
1125
+ url: URL | str,
1126
+ *,
1127
+ content: RequestContent | None = None,
1128
+ data: RequestData | None = None,
1129
+ files: RequestFiles | None = None,
1130
+ json: typing.Any | None = None,
1131
+ params: QueryParamTypes | None = None,
1132
+ headers: HeaderTypes | None = None,
1133
+ cookies: CookieTypes | None = None,
1134
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1135
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1136
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1137
+ extensions: RequestExtensions | None = None,
1138
+ ) -> Response:
1139
+ """
1140
+ Send a `POST` request.
1141
+
1142
+ **Parameters**: See `httpx.request`.
1143
+ """
1144
+ return self.request(
1145
+ "POST",
1146
+ url,
1147
+ content=content,
1148
+ data=data,
1149
+ files=files,
1150
+ json=json,
1151
+ params=params,
1152
+ headers=headers,
1153
+ cookies=cookies,
1154
+ auth=auth,
1155
+ follow_redirects=follow_redirects,
1156
+ timeout=timeout,
1157
+ extensions=extensions,
1158
+ )
1159
+
1160
+ def put(
1161
+ self,
1162
+ url: URL | str,
1163
+ *,
1164
+ content: RequestContent | None = None,
1165
+ data: RequestData | None = None,
1166
+ files: RequestFiles | None = None,
1167
+ json: typing.Any | None = None,
1168
+ params: QueryParamTypes | None = None,
1169
+ headers: HeaderTypes | None = None,
1170
+ cookies: CookieTypes | None = None,
1171
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1172
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1173
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1174
+ extensions: RequestExtensions | None = None,
1175
+ ) -> Response:
1176
+ """
1177
+ Send a `PUT` request.
1178
+
1179
+ **Parameters**: See `httpx.request`.
1180
+ """
1181
+ return self.request(
1182
+ "PUT",
1183
+ url,
1184
+ content=content,
1185
+ data=data,
1186
+ files=files,
1187
+ json=json,
1188
+ params=params,
1189
+ headers=headers,
1190
+ cookies=cookies,
1191
+ auth=auth,
1192
+ follow_redirects=follow_redirects,
1193
+ timeout=timeout,
1194
+ extensions=extensions,
1195
+ )
1196
+
1197
+ def patch(
1198
+ self,
1199
+ url: URL | str,
1200
+ *,
1201
+ content: RequestContent | None = None,
1202
+ data: RequestData | None = None,
1203
+ files: RequestFiles | None = None,
1204
+ json: typing.Any | None = None,
1205
+ params: QueryParamTypes | None = None,
1206
+ headers: HeaderTypes | None = None,
1207
+ cookies: CookieTypes | None = None,
1208
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1209
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1210
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1211
+ extensions: RequestExtensions | None = None,
1212
+ ) -> Response:
1213
+ """
1214
+ Send a `PATCH` request.
1215
+
1216
+ **Parameters**: See `httpx.request`.
1217
+ """
1218
+ return self.request(
1219
+ "PATCH",
1220
+ url,
1221
+ content=content,
1222
+ data=data,
1223
+ files=files,
1224
+ json=json,
1225
+ params=params,
1226
+ headers=headers,
1227
+ cookies=cookies,
1228
+ auth=auth,
1229
+ follow_redirects=follow_redirects,
1230
+ timeout=timeout,
1231
+ extensions=extensions,
1232
+ )
1233
+
1234
+ def delete(
1235
+ self,
1236
+ url: URL | str,
1237
+ *,
1238
+ params: QueryParamTypes | None = None,
1239
+ headers: HeaderTypes | None = None,
1240
+ cookies: CookieTypes | None = None,
1241
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1242
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1243
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1244
+ extensions: RequestExtensions | None = None,
1245
+ ) -> Response:
1246
+ """
1247
+ Send a `DELETE` request.
1248
+
1249
+ **Parameters**: See `httpx.request`.
1250
+ """
1251
+ return self.request(
1252
+ "DELETE",
1253
+ url,
1254
+ params=params,
1255
+ headers=headers,
1256
+ cookies=cookies,
1257
+ auth=auth,
1258
+ follow_redirects=follow_redirects,
1259
+ timeout=timeout,
1260
+ extensions=extensions,
1261
+ )
1262
+
1263
+ def close(self) -> None:
1264
+ """
1265
+ Close transport and proxies.
1266
+ """
1267
+ if self._state != ClientState.CLOSED:
1268
+ self._state = ClientState.CLOSED
1269
+
1270
+ self._transport.close()
1271
+ for transport in self._mounts.values():
1272
+ if transport is not None:
1273
+ transport.close()
1274
+
1275
+ def __enter__(self: T) -> T:
1276
+ if self._state != ClientState.UNOPENED:
1277
+ msg = {
1278
+ ClientState.OPENED: "Cannot open a client instance more than once.",
1279
+ ClientState.CLOSED: (
1280
+ "Cannot reopen a client instance, once it has been closed."
1281
+ ),
1282
+ }[self._state]
1283
+ raise RuntimeError(msg)
1284
+
1285
+ self._state = ClientState.OPENED
1286
+
1287
+ self._transport.__enter__()
1288
+ for transport in self._mounts.values():
1289
+ if transport is not None:
1290
+ transport.__enter__()
1291
+ return self
1292
+
1293
+ def __exit__(
1294
+ self,
1295
+ exc_type: type[BaseException] | None = None,
1296
+ exc_value: BaseException | None = None,
1297
+ traceback: TracebackType | None = None,
1298
+ ) -> None:
1299
+ self._state = ClientState.CLOSED
1300
+
1301
+ self._transport.__exit__(exc_type, exc_value, traceback)
1302
+ for transport in self._mounts.values():
1303
+ if transport is not None:
1304
+ transport.__exit__(exc_type, exc_value, traceback)
1305
+
1306
+
1307
+ class AsyncClient(BaseClient):
1308
+ """
1309
+ An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,
1310
+ cookie persistence, etc.
1311
+
1312
+ It can be shared between tasks.
1313
+
1314
+ Usage:
1315
+
1316
+ ```python
1317
+ >>> async with httpx.AsyncClient() as client:
1318
+ >>> response = await client.get('https://example.org')
1319
+ ```
1320
+
1321
+ **Parameters:**
1322
+
1323
+ * **auth** - *(optional)* An authentication class to use when sending
1324
+ requests.
1325
+ * **params** - *(optional)* Query parameters to include in request URLs, as
1326
+ a string, dictionary, or sequence of two-tuples.
1327
+ * **headers** - *(optional)* Dictionary of HTTP headers to include when
1328
+ sending requests.
1329
+ * **cookies** - *(optional)* Dictionary of Cookie items to include when
1330
+ sending requests.
1331
+ * **verify** - *(optional)* Either `True` to use an SSL context with the
1332
+ default CA bundle, `False` to disable verification, or an instance of
1333
+ `ssl.SSLContext` to use a custom context.
1334
+ * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
1335
+ enabled. Defaults to `False`.
1336
+ * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
1337
+ * **timeout** - *(optional)* The timeout configuration to use when sending
1338
+ requests.
1339
+ * **limits** - *(optional)* The limits configuration to use.
1340
+ * **max_redirects** - *(optional)* The maximum number of redirect responses
1341
+ that should be followed.
1342
+ * **base_url** - *(optional)* A URL to use as the base when building
1343
+ request URLs.
1344
+ * **transport** - *(optional)* A transport class to use for sending requests
1345
+ over the network.
1346
+ * **trust_env** - *(optional)* Enables or disables usage of environment
1347
+ variables for configuration.
1348
+ * **default_encoding** - *(optional)* The default encoding to use for decoding
1349
+ response text, if no charset information is included in a response Content-Type
1350
+ header. Set to a callable for automatic character set detection. Default: "utf-8".
1351
+ """
1352
+
1353
+ def __init__(
1354
+ self,
1355
+ *,
1356
+ auth: AuthTypes | None = None,
1357
+ params: QueryParamTypes | None = None,
1358
+ headers: HeaderTypes | None = None,
1359
+ cookies: CookieTypes | None = None,
1360
+ verify: ssl.SSLContext | str | bool = True,
1361
+ cert: CertTypes | None = None,
1362
+ http1: bool = True,
1363
+ http2: bool = False,
1364
+ proxy: ProxyTypes | None = None,
1365
+ mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
1366
+ timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
1367
+ follow_redirects: bool = False,
1368
+ limits: Limits = DEFAULT_LIMITS,
1369
+ max_redirects: int = DEFAULT_MAX_REDIRECTS,
1370
+ event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
1371
+ base_url: URL | str = "",
1372
+ transport: AsyncBaseTransport | None = None,
1373
+ trust_env: bool = True,
1374
+ default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
1375
+ ) -> None:
1376
+ super().__init__(
1377
+ auth=auth,
1378
+ params=params,
1379
+ headers=headers,
1380
+ cookies=cookies,
1381
+ timeout=timeout,
1382
+ follow_redirects=follow_redirects,
1383
+ max_redirects=max_redirects,
1384
+ event_hooks=event_hooks,
1385
+ base_url=base_url,
1386
+ trust_env=trust_env,
1387
+ default_encoding=default_encoding,
1388
+ )
1389
+
1390
+ if http2:
1391
+ try:
1392
+ import h2 # noqa
1393
+ except ImportError: # pragma: no cover
1394
+ raise ImportError(
1395
+ "Using http2=True, but the 'h2' package is not installed. "
1396
+ "Make sure to install httpx using `pip install httpx[http2]`."
1397
+ ) from None
1398
+
1399
+ allow_env_proxies = trust_env and transport is None
1400
+ proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
1401
+
1402
+ self._transport = self._init_transport(
1403
+ verify=verify,
1404
+ cert=cert,
1405
+ trust_env=trust_env,
1406
+ http1=http1,
1407
+ http2=http2,
1408
+ limits=limits,
1409
+ transport=transport,
1410
+ )
1411
+
1412
+ self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {
1413
+ URLPattern(key): None
1414
+ if proxy is None
1415
+ else self._init_proxy_transport(
1416
+ proxy,
1417
+ verify=verify,
1418
+ cert=cert,
1419
+ trust_env=trust_env,
1420
+ http1=http1,
1421
+ http2=http2,
1422
+ limits=limits,
1423
+ )
1424
+ for key, proxy in proxy_map.items()
1425
+ }
1426
+ if mounts is not None:
1427
+ self._mounts.update(
1428
+ {URLPattern(key): transport for key, transport in mounts.items()}
1429
+ )
1430
+ self._mounts = dict(sorted(self._mounts.items()))
1431
+
1432
+ def _init_transport(
1433
+ self,
1434
+ verify: ssl.SSLContext | str | bool = True,
1435
+ cert: CertTypes | None = None,
1436
+ trust_env: bool = True,
1437
+ http1: bool = True,
1438
+ http2: bool = False,
1439
+ limits: Limits = DEFAULT_LIMITS,
1440
+ transport: AsyncBaseTransport | None = None,
1441
+ ) -> AsyncBaseTransport:
1442
+ if transport is not None:
1443
+ return transport
1444
+
1445
+ return AsyncHTTPTransport(
1446
+ verify=verify,
1447
+ cert=cert,
1448
+ trust_env=trust_env,
1449
+ http1=http1,
1450
+ http2=http2,
1451
+ limits=limits,
1452
+ )
1453
+
1454
+ def _init_proxy_transport(
1455
+ self,
1456
+ proxy: Proxy,
1457
+ verify: ssl.SSLContext | str | bool = True,
1458
+ cert: CertTypes | None = None,
1459
+ trust_env: bool = True,
1460
+ http1: bool = True,
1461
+ http2: bool = False,
1462
+ limits: Limits = DEFAULT_LIMITS,
1463
+ ) -> AsyncBaseTransport:
1464
+ return AsyncHTTPTransport(
1465
+ verify=verify,
1466
+ cert=cert,
1467
+ trust_env=trust_env,
1468
+ http1=http1,
1469
+ http2=http2,
1470
+ limits=limits,
1471
+ proxy=proxy,
1472
+ )
1473
+
1474
+ def _transport_for_url(self, url: URL) -> AsyncBaseTransport:
1475
+ """
1476
+ Returns the transport instance that should be used for a given URL.
1477
+ This will either be the standard connection pool, or a proxy.
1478
+ """
1479
+ for pattern, transport in self._mounts.items():
1480
+ if pattern.matches(url):
1481
+ return self._transport if transport is None else transport
1482
+
1483
+ return self._transport
1484
+
1485
+ async def request(
1486
+ self,
1487
+ method: str,
1488
+ url: URL | str,
1489
+ *,
1490
+ content: RequestContent | None = None,
1491
+ data: RequestData | None = None,
1492
+ files: RequestFiles | None = None,
1493
+ json: typing.Any | None = None,
1494
+ params: QueryParamTypes | None = None,
1495
+ headers: HeaderTypes | None = None,
1496
+ cookies: CookieTypes | None = None,
1497
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1498
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1499
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1500
+ extensions: RequestExtensions | None = None,
1501
+ ) -> Response:
1502
+ """
1503
+ Build and send a request.
1504
+
1505
+ Equivalent to:
1506
+
1507
+ ```python
1508
+ request = client.build_request(...)
1509
+ response = await client.send(request, ...)
1510
+ ```
1511
+
1512
+ See `AsyncClient.build_request()`, `AsyncClient.send()`
1513
+ and [Merging of configuration][0] for how the various parameters
1514
+ are merged with client-level configuration.
1515
+
1516
+ [0]: /advanced/clients/#merging-of-configuration
1517
+ """
1518
+
1519
+ if cookies is not None: # pragma: no cover
1520
+ message = (
1521
+ "Setting per-request cookies=<...> is being deprecated, because "
1522
+ "the expected behaviour on cookie persistence is ambiguous. Set "
1523
+ "cookies directly on the client instance instead."
1524
+ )
1525
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
1526
+
1527
+ request = self.build_request(
1528
+ method=method,
1529
+ url=url,
1530
+ content=content,
1531
+ data=data,
1532
+ files=files,
1533
+ json=json,
1534
+ params=params,
1535
+ headers=headers,
1536
+ cookies=cookies,
1537
+ timeout=timeout,
1538
+ extensions=extensions,
1539
+ )
1540
+ return await self.send(request, auth=auth, follow_redirects=follow_redirects)
1541
+
1542
+ @asynccontextmanager
1543
+ async def stream(
1544
+ self,
1545
+ method: str,
1546
+ url: URL | str,
1547
+ *,
1548
+ content: RequestContent | None = None,
1549
+ data: RequestData | None = None,
1550
+ files: RequestFiles | None = None,
1551
+ json: typing.Any | None = None,
1552
+ params: QueryParamTypes | None = None,
1553
+ headers: HeaderTypes | None = None,
1554
+ cookies: CookieTypes | None = None,
1555
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1556
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1557
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1558
+ extensions: RequestExtensions | None = None,
1559
+ ) -> typing.AsyncIterator[Response]:
1560
+ """
1561
+ Alternative to `httpx.request()` that streams the response body
1562
+ instead of loading it into memory at once.
1563
+
1564
+ **Parameters**: See `httpx.request`.
1565
+
1566
+ See also: [Streaming Responses][0]
1567
+
1568
+ [0]: /quickstart#streaming-responses
1569
+ """
1570
+ request = self.build_request(
1571
+ method=method,
1572
+ url=url,
1573
+ content=content,
1574
+ data=data,
1575
+ files=files,
1576
+ json=json,
1577
+ params=params,
1578
+ headers=headers,
1579
+ cookies=cookies,
1580
+ timeout=timeout,
1581
+ extensions=extensions,
1582
+ )
1583
+ response = await self.send(
1584
+ request=request,
1585
+ auth=auth,
1586
+ follow_redirects=follow_redirects,
1587
+ stream=True,
1588
+ )
1589
+ try:
1590
+ yield response
1591
+ finally:
1592
+ await response.aclose()
1593
+
1594
+ async def send(
1595
+ self,
1596
+ request: Request,
1597
+ *,
1598
+ stream: bool = False,
1599
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1600
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1601
+ ) -> Response:
1602
+ """
1603
+ Send a request.
1604
+
1605
+ The request is sent as-is, unmodified.
1606
+
1607
+ Typically you'll want to build one with `AsyncClient.build_request()`
1608
+ so that any client-level configuration is merged into the request,
1609
+ but passing an explicit `httpx.Request()` is supported as well.
1610
+
1611
+ See also: [Request instances][0]
1612
+
1613
+ [0]: /advanced/clients/#request-instances
1614
+ """
1615
+ if self._state == ClientState.CLOSED:
1616
+ raise RuntimeError("Cannot send a request, as the client has been closed.")
1617
+
1618
+ self._state = ClientState.OPENED
1619
+ follow_redirects = (
1620
+ self.follow_redirects
1621
+ if isinstance(follow_redirects, UseClientDefault)
1622
+ else follow_redirects
1623
+ )
1624
+
1625
+ self._set_timeout(request)
1626
+
1627
+ auth = self._build_request_auth(request, auth)
1628
+
1629
+ response = await self._send_handling_auth(
1630
+ request,
1631
+ auth=auth,
1632
+ follow_redirects=follow_redirects,
1633
+ history=[],
1634
+ )
1635
+ try:
1636
+ if not stream:
1637
+ await response.aread()
1638
+
1639
+ return response
1640
+
1641
+ except BaseException as exc:
1642
+ await response.aclose()
1643
+ raise exc
1644
+
1645
+ async def _send_handling_auth(
1646
+ self,
1647
+ request: Request,
1648
+ auth: Auth,
1649
+ follow_redirects: bool,
1650
+ history: list[Response],
1651
+ ) -> Response:
1652
+ auth_flow = auth.async_auth_flow(request)
1653
+ try:
1654
+ request = await auth_flow.__anext__()
1655
+
1656
+ while True:
1657
+ response = await self._send_handling_redirects(
1658
+ request,
1659
+ follow_redirects=follow_redirects,
1660
+ history=history,
1661
+ )
1662
+ try:
1663
+ try:
1664
+ next_request = await auth_flow.asend(response)
1665
+ except StopAsyncIteration:
1666
+ return response
1667
+
1668
+ response.history = list(history)
1669
+ await response.aread()
1670
+ request = next_request
1671
+ history.append(response)
1672
+
1673
+ except BaseException as exc:
1674
+ await response.aclose()
1675
+ raise exc
1676
+ finally:
1677
+ await auth_flow.aclose()
1678
+
1679
+ async def _send_handling_redirects(
1680
+ self,
1681
+ request: Request,
1682
+ follow_redirects: bool,
1683
+ history: list[Response],
1684
+ ) -> Response:
1685
+ while True:
1686
+ if len(history) > self.max_redirects:
1687
+ raise TooManyRedirects(
1688
+ "Exceeded maximum allowed redirects.", request=request
1689
+ )
1690
+
1691
+ for hook in self._event_hooks["request"]:
1692
+ await hook(request)
1693
+
1694
+ response = await self._send_single_request(request)
1695
+ try:
1696
+ for hook in self._event_hooks["response"]:
1697
+ await hook(response)
1698
+
1699
+ response.history = list(history)
1700
+
1701
+ if not response.has_redirect_location:
1702
+ return response
1703
+
1704
+ request = self._build_redirect_request(request, response)
1705
+ history = history + [response]
1706
+
1707
+ if follow_redirects:
1708
+ await response.aread()
1709
+ else:
1710
+ response.next_request = request
1711
+ return response
1712
+
1713
+ except BaseException as exc:
1714
+ await response.aclose()
1715
+ raise exc
1716
+
1717
+ async def _send_single_request(self, request: Request) -> Response:
1718
+ """
1719
+ Sends a single request, without handling any redirections.
1720
+ """
1721
+ transport = self._transport_for_url(request.url)
1722
+ start = time.perf_counter()
1723
+
1724
+ if not isinstance(request.stream, AsyncByteStream):
1725
+ raise RuntimeError(
1726
+ "Attempted to send an sync request with an AsyncClient instance."
1727
+ )
1728
+
1729
+ with request_context(request=request):
1730
+ response = await transport.handle_async_request(request)
1731
+
1732
+ assert isinstance(response.stream, AsyncByteStream)
1733
+ response.request = request
1734
+ response.stream = BoundAsyncStream(
1735
+ response.stream, response=response, start=start
1736
+ )
1737
+ self.cookies.extract_cookies(response)
1738
+ response.default_encoding = self._default_encoding
1739
+
1740
+ logger.info(
1741
+ 'HTTP Request: %s %s "%s %d %s"',
1742
+ request.method,
1743
+ request.url,
1744
+ response.http_version,
1745
+ response.status_code,
1746
+ response.reason_phrase,
1747
+ )
1748
+
1749
+ return response
1750
+
1751
+ async def get(
1752
+ self,
1753
+ url: URL | str,
1754
+ *,
1755
+ params: QueryParamTypes | None = None,
1756
+ headers: HeaderTypes | None = None,
1757
+ cookies: CookieTypes | None = None,
1758
+ auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
1759
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1760
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1761
+ extensions: RequestExtensions | None = None,
1762
+ ) -> Response:
1763
+ """
1764
+ Send a `GET` request.
1765
+
1766
+ **Parameters**: See `httpx.request`.
1767
+ """
1768
+ return await self.request(
1769
+ "GET",
1770
+ url,
1771
+ params=params,
1772
+ headers=headers,
1773
+ cookies=cookies,
1774
+ auth=auth,
1775
+ follow_redirects=follow_redirects,
1776
+ timeout=timeout,
1777
+ extensions=extensions,
1778
+ )
1779
+
1780
+ async def options(
1781
+ self,
1782
+ url: URL | str,
1783
+ *,
1784
+ params: QueryParamTypes | None = None,
1785
+ headers: HeaderTypes | None = None,
1786
+ cookies: CookieTypes | None = None,
1787
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1788
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1789
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1790
+ extensions: RequestExtensions | None = None,
1791
+ ) -> Response:
1792
+ """
1793
+ Send an `OPTIONS` request.
1794
+
1795
+ **Parameters**: See `httpx.request`.
1796
+ """
1797
+ return await self.request(
1798
+ "OPTIONS",
1799
+ url,
1800
+ params=params,
1801
+ headers=headers,
1802
+ cookies=cookies,
1803
+ auth=auth,
1804
+ follow_redirects=follow_redirects,
1805
+ timeout=timeout,
1806
+ extensions=extensions,
1807
+ )
1808
+
1809
+ async def head(
1810
+ self,
1811
+ url: URL | str,
1812
+ *,
1813
+ params: QueryParamTypes | None = None,
1814
+ headers: HeaderTypes | None = None,
1815
+ cookies: CookieTypes | None = None,
1816
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1817
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1818
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1819
+ extensions: RequestExtensions | None = None,
1820
+ ) -> Response:
1821
+ """
1822
+ Send a `HEAD` request.
1823
+
1824
+ **Parameters**: See `httpx.request`.
1825
+ """
1826
+ return await self.request(
1827
+ "HEAD",
1828
+ url,
1829
+ params=params,
1830
+ headers=headers,
1831
+ cookies=cookies,
1832
+ auth=auth,
1833
+ follow_redirects=follow_redirects,
1834
+ timeout=timeout,
1835
+ extensions=extensions,
1836
+ )
1837
+
1838
+ async def post(
1839
+ self,
1840
+ url: URL | str,
1841
+ *,
1842
+ content: RequestContent | None = None,
1843
+ data: RequestData | None = None,
1844
+ files: RequestFiles | None = None,
1845
+ json: typing.Any | None = None,
1846
+ params: QueryParamTypes | None = None,
1847
+ headers: HeaderTypes | None = None,
1848
+ cookies: CookieTypes | None = None,
1849
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1850
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1851
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1852
+ extensions: RequestExtensions | None = None,
1853
+ ) -> Response:
1854
+ """
1855
+ Send a `POST` request.
1856
+
1857
+ **Parameters**: See `httpx.request`.
1858
+ """
1859
+ return await self.request(
1860
+ "POST",
1861
+ url,
1862
+ content=content,
1863
+ data=data,
1864
+ files=files,
1865
+ json=json,
1866
+ params=params,
1867
+ headers=headers,
1868
+ cookies=cookies,
1869
+ auth=auth,
1870
+ follow_redirects=follow_redirects,
1871
+ timeout=timeout,
1872
+ extensions=extensions,
1873
+ )
1874
+
1875
+ async def put(
1876
+ self,
1877
+ url: URL | str,
1878
+ *,
1879
+ content: RequestContent | None = None,
1880
+ data: RequestData | None = None,
1881
+ files: RequestFiles | None = None,
1882
+ json: typing.Any | None = None,
1883
+ params: QueryParamTypes | None = None,
1884
+ headers: HeaderTypes | None = None,
1885
+ cookies: CookieTypes | None = None,
1886
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1887
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1888
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1889
+ extensions: RequestExtensions | None = None,
1890
+ ) -> Response:
1891
+ """
1892
+ Send a `PUT` request.
1893
+
1894
+ **Parameters**: See `httpx.request`.
1895
+ """
1896
+ return await self.request(
1897
+ "PUT",
1898
+ url,
1899
+ content=content,
1900
+ data=data,
1901
+ files=files,
1902
+ json=json,
1903
+ params=params,
1904
+ headers=headers,
1905
+ cookies=cookies,
1906
+ auth=auth,
1907
+ follow_redirects=follow_redirects,
1908
+ timeout=timeout,
1909
+ extensions=extensions,
1910
+ )
1911
+
1912
+ async def patch(
1913
+ self,
1914
+ url: URL | str,
1915
+ *,
1916
+ content: RequestContent | None = None,
1917
+ data: RequestData | None = None,
1918
+ files: RequestFiles | None = None,
1919
+ json: typing.Any | None = None,
1920
+ params: QueryParamTypes | None = None,
1921
+ headers: HeaderTypes | None = None,
1922
+ cookies: CookieTypes | None = None,
1923
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1924
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1925
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1926
+ extensions: RequestExtensions | None = None,
1927
+ ) -> Response:
1928
+ """
1929
+ Send a `PATCH` request.
1930
+
1931
+ **Parameters**: See `httpx.request`.
1932
+ """
1933
+ return await self.request(
1934
+ "PATCH",
1935
+ url,
1936
+ content=content,
1937
+ data=data,
1938
+ files=files,
1939
+ json=json,
1940
+ params=params,
1941
+ headers=headers,
1942
+ cookies=cookies,
1943
+ auth=auth,
1944
+ follow_redirects=follow_redirects,
1945
+ timeout=timeout,
1946
+ extensions=extensions,
1947
+ )
1948
+
1949
+ async def delete(
1950
+ self,
1951
+ url: URL | str,
1952
+ *,
1953
+ params: QueryParamTypes | None = None,
1954
+ headers: HeaderTypes | None = None,
1955
+ cookies: CookieTypes | None = None,
1956
+ auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1957
+ follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1958
+ timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1959
+ extensions: RequestExtensions | None = None,
1960
+ ) -> Response:
1961
+ """
1962
+ Send a `DELETE` request.
1963
+
1964
+ **Parameters**: See `httpx.request`.
1965
+ """
1966
+ return await self.request(
1967
+ "DELETE",
1968
+ url,
1969
+ params=params,
1970
+ headers=headers,
1971
+ cookies=cookies,
1972
+ auth=auth,
1973
+ follow_redirects=follow_redirects,
1974
+ timeout=timeout,
1975
+ extensions=extensions,
1976
+ )
1977
+
1978
+ async def aclose(self) -> None:
1979
+ """
1980
+ Close transport and proxies.
1981
+ """
1982
+ if self._state != ClientState.CLOSED:
1983
+ self._state = ClientState.CLOSED
1984
+
1985
+ await self._transport.aclose()
1986
+ for proxy in self._mounts.values():
1987
+ if proxy is not None:
1988
+ await proxy.aclose()
1989
+
1990
+ async def __aenter__(self: U) -> U:
1991
+ if self._state != ClientState.UNOPENED:
1992
+ msg = {
1993
+ ClientState.OPENED: "Cannot open a client instance more than once.",
1994
+ ClientState.CLOSED: (
1995
+ "Cannot reopen a client instance, once it has been closed."
1996
+ ),
1997
+ }[self._state]
1998
+ raise RuntimeError(msg)
1999
+
2000
+ self._state = ClientState.OPENED
2001
+
2002
+ await self._transport.__aenter__()
2003
+ for proxy in self._mounts.values():
2004
+ if proxy is not None:
2005
+ await proxy.__aenter__()
2006
+ return self
2007
+
2008
+ async def __aexit__(
2009
+ self,
2010
+ exc_type: type[BaseException] | None = None,
2011
+ exc_value: BaseException | None = None,
2012
+ traceback: TracebackType | None = None,
2013
+ ) -> None:
2014
+ self._state = ClientState.CLOSED
2015
+
2016
+ await self._transport.__aexit__(exc_type, exc_value, traceback)
2017
+ for proxy in self._mounts.values():
2018
+ if proxy is not None:
2019
+ await proxy.__aexit__(exc_type, exc_value, traceback)
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_decoders.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handlers for Content-Encoding.
3
+
4
+ See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import codecs
10
+ import io
11
+ import typing
12
+ import zlib
13
+
14
+ from ._exceptions import DecodingError
15
+
16
+ # Brotli support is optional
17
+ try:
18
+ # The C bindings in `brotli` are recommended for CPython.
19
+ import brotli
20
+ except ImportError: # pragma: no cover
21
+ try:
22
+ # The CFFI bindings in `brotlicffi` are recommended for PyPy
23
+ # and other environments.
24
+ import brotlicffi as brotli
25
+ except ImportError:
26
+ brotli = None
27
+
28
+
29
+ # Zstandard support is optional
30
+ try:
31
+ import zstandard
32
+ except ImportError: # pragma: no cover
33
+ zstandard = None # type: ignore
34
+
35
+
36
+ class ContentDecoder:
37
+ def decode(self, data: bytes) -> bytes:
38
+ raise NotImplementedError() # pragma: no cover
39
+
40
+ def flush(self) -> bytes:
41
+ raise NotImplementedError() # pragma: no cover
42
+
43
+
44
+ class IdentityDecoder(ContentDecoder):
45
+ """
46
+ Handle unencoded data.
47
+ """
48
+
49
+ def decode(self, data: bytes) -> bytes:
50
+ return data
51
+
52
+ def flush(self) -> bytes:
53
+ return b""
54
+
55
+
56
+ class DeflateDecoder(ContentDecoder):
57
+ """
58
+ Handle 'deflate' decoding.
59
+
60
+ See: https://stackoverflow.com/questions/1838699
61
+ """
62
+
63
+ def __init__(self) -> None:
64
+ self.first_attempt = True
65
+ self.decompressor = zlib.decompressobj()
66
+
67
+ def decode(self, data: bytes) -> bytes:
68
+ was_first_attempt = self.first_attempt
69
+ self.first_attempt = False
70
+ try:
71
+ return self.decompressor.decompress(data)
72
+ except zlib.error as exc:
73
+ if was_first_attempt:
74
+ self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
75
+ return self.decode(data)
76
+ raise DecodingError(str(exc)) from exc
77
+
78
+ def flush(self) -> bytes:
79
+ try:
80
+ return self.decompressor.flush()
81
+ except zlib.error as exc: # pragma: no cover
82
+ raise DecodingError(str(exc)) from exc
83
+
84
+
85
+ class GZipDecoder(ContentDecoder):
86
+ """
87
+ Handle 'gzip' decoding.
88
+
89
+ See: https://stackoverflow.com/questions/1838699
90
+ """
91
+
92
+ def __init__(self) -> None:
93
+ self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)
94
+
95
+ def decode(self, data: bytes) -> bytes:
96
+ try:
97
+ return self.decompressor.decompress(data)
98
+ except zlib.error as exc:
99
+ raise DecodingError(str(exc)) from exc
100
+
101
+ def flush(self) -> bytes:
102
+ try:
103
+ return self.decompressor.flush()
104
+ except zlib.error as exc: # pragma: no cover
105
+ raise DecodingError(str(exc)) from exc
106
+
107
+
108
+ class BrotliDecoder(ContentDecoder):
109
+ """
110
+ Handle 'brotli' decoding.
111
+
112
+ Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/
113
+ or `pip install brotli`. See https://github.com/google/brotli
114
+ Supports both 'brotlipy' and 'Brotli' packages since they share an import
115
+ name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'
116
+ """
117
+
118
+ def __init__(self) -> None:
119
+ if brotli is None: # pragma: no cover
120
+ raise ImportError(
121
+ "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' "
122
+ "packages have been installed. "
123
+ "Make sure to install httpx using `pip install httpx[brotli]`."
124
+ ) from None
125
+
126
+ self.decompressor = brotli.Decompressor()
127
+ self.seen_data = False
128
+ self._decompress: typing.Callable[[bytes], bytes]
129
+ if hasattr(self.decompressor, "decompress"):
130
+ # The 'brotlicffi' package.
131
+ self._decompress = self.decompressor.decompress # pragma: no cover
132
+ else:
133
+ # The 'brotli' package.
134
+ self._decompress = self.decompressor.process # pragma: no cover
135
+
136
+ def decode(self, data: bytes) -> bytes:
137
+ if not data:
138
+ return b""
139
+ self.seen_data = True
140
+ try:
141
+ return self._decompress(data)
142
+ except brotli.error as exc:
143
+ raise DecodingError(str(exc)) from exc
144
+
145
+ def flush(self) -> bytes:
146
+ if not self.seen_data:
147
+ return b""
148
+ try:
149
+ if hasattr(self.decompressor, "finish"):
150
+ # Only available in the 'brotlicffi' package.
151
+
152
+ # As the decompressor decompresses eagerly, this
153
+ # will never actually emit any data. However, it will potentially throw
154
+ # errors if a truncated or damaged data stream has been used.
155
+ self.decompressor.finish() # pragma: no cover
156
+ return b""
157
+ except brotli.error as exc: # pragma: no cover
158
+ raise DecodingError(str(exc)) from exc
159
+
160
+
161
+ class ZStandardDecoder(ContentDecoder):
162
+ """
163
+ Handle 'zstd' RFC 8878 decoding.
164
+
165
+ Requires `pip install zstandard`.
166
+ Can be installed as a dependency of httpx using `pip install httpx[zstd]`.
167
+ """
168
+
169
+ # inspired by the ZstdDecoder implementation in urllib3
170
+ def __init__(self) -> None:
171
+ if zstandard is None: # pragma: no cover
172
+ raise ImportError(
173
+ "Using 'ZStandardDecoder', ..."
174
+ "Make sure to install httpx using `pip install httpx[zstd]`."
175
+ ) from None
176
+
177
+ self.decompressor = zstandard.ZstdDecompressor().decompressobj()
178
+ self.seen_data = False
179
+
180
+ def decode(self, data: bytes) -> bytes:
181
+ assert zstandard is not None
182
+ self.seen_data = True
183
+ output = io.BytesIO()
184
+ try:
185
+ output.write(self.decompressor.decompress(data))
186
+ while self.decompressor.eof and self.decompressor.unused_data:
187
+ unused_data = self.decompressor.unused_data
188
+ self.decompressor = zstandard.ZstdDecompressor().decompressobj()
189
+ output.write(self.decompressor.decompress(unused_data))
190
+ except zstandard.ZstdError as exc:
191
+ raise DecodingError(str(exc)) from exc
192
+ return output.getvalue()
193
+
194
+ def flush(self) -> bytes:
195
+ if not self.seen_data:
196
+ return b""
197
+ ret = self.decompressor.flush() # note: this is a no-op
198
+ if not self.decompressor.eof:
199
+ raise DecodingError("Zstandard data is incomplete") # pragma: no cover
200
+ return bytes(ret)
201
+
202
+
203
+ class MultiDecoder(ContentDecoder):
204
+ """
205
+ Handle the case where multiple encodings have been applied.
206
+ """
207
+
208
+ def __init__(self, children: typing.Sequence[ContentDecoder]) -> None:
209
+ """
210
+ 'children' should be a sequence of decoders in the order in which
211
+ each was applied.
212
+ """
213
+ # Note that we reverse the order for decoding.
214
+ self.children = list(reversed(children))
215
+
216
+ def decode(self, data: bytes) -> bytes:
217
+ for child in self.children:
218
+ data = child.decode(data)
219
+ return data
220
+
221
+ def flush(self) -> bytes:
222
+ data = b""
223
+ for child in self.children:
224
+ data = child.decode(data) + child.flush()
225
+ return data
226
+
227
+
228
+ class ByteChunker:
229
+ """
230
+ Handles returning byte content in fixed-size chunks.
231
+ """
232
+
233
+ def __init__(self, chunk_size: int | None = None) -> None:
234
+ self._buffer = io.BytesIO()
235
+ self._chunk_size = chunk_size
236
+
237
+ def decode(self, content: bytes) -> list[bytes]:
238
+ if self._chunk_size is None:
239
+ return [content] if content else []
240
+
241
+ self._buffer.write(content)
242
+ if self._buffer.tell() >= self._chunk_size:
243
+ value = self._buffer.getvalue()
244
+ chunks = [
245
+ value[i : i + self._chunk_size]
246
+ for i in range(0, len(value), self._chunk_size)
247
+ ]
248
+ if len(chunks[-1]) == self._chunk_size:
249
+ self._buffer.seek(0)
250
+ self._buffer.truncate()
251
+ return chunks
252
+ else:
253
+ self._buffer.seek(0)
254
+ self._buffer.write(chunks[-1])
255
+ self._buffer.truncate()
256
+ return chunks[:-1]
257
+ else:
258
+ return []
259
+
260
+ def flush(self) -> list[bytes]:
261
+ value = self._buffer.getvalue()
262
+ self._buffer.seek(0)
263
+ self._buffer.truncate()
264
+ return [value] if value else []
265
+
266
+
267
+ class TextChunker:
268
+ """
269
+ Handles returning text content in fixed-size chunks.
270
+ """
271
+
272
+ def __init__(self, chunk_size: int | None = None) -> None:
273
+ self._buffer = io.StringIO()
274
+ self._chunk_size = chunk_size
275
+
276
+ def decode(self, content: str) -> list[str]:
277
+ if self._chunk_size is None:
278
+ return [content] if content else []
279
+
280
+ self._buffer.write(content)
281
+ if self._buffer.tell() >= self._chunk_size:
282
+ value = self._buffer.getvalue()
283
+ chunks = [
284
+ value[i : i + self._chunk_size]
285
+ for i in range(0, len(value), self._chunk_size)
286
+ ]
287
+ if len(chunks[-1]) == self._chunk_size:
288
+ self._buffer.seek(0)
289
+ self._buffer.truncate()
290
+ return chunks
291
+ else:
292
+ self._buffer.seek(0)
293
+ self._buffer.write(chunks[-1])
294
+ self._buffer.truncate()
295
+ return chunks[:-1]
296
+ else:
297
+ return []
298
+
299
+ def flush(self) -> list[str]:
300
+ value = self._buffer.getvalue()
301
+ self._buffer.seek(0)
302
+ self._buffer.truncate()
303
+ return [value] if value else []
304
+
305
+
306
+ class TextDecoder:
307
+ """
308
+ Handles incrementally decoding bytes into text
309
+ """
310
+
311
+ def __init__(self, encoding: str = "utf-8") -> None:
312
+ self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace")
313
+
314
+ def decode(self, data: bytes) -> str:
315
+ return self.decoder.decode(data)
316
+
317
+ def flush(self) -> str:
318
+ return self.decoder.decode(b"", True)
319
+
320
+
321
+ class LineDecoder:
322
+ """
323
+ Handles incrementally reading lines from text.
324
+
325
+ Has the same behaviour as the stdllib splitlines,
326
+ but handling the input iteratively.
327
+ """
328
+
329
+ def __init__(self) -> None:
330
+ self.buffer: list[str] = []
331
+ self.trailing_cr: bool = False
332
+
333
+ def decode(self, text: str) -> list[str]:
334
+ # See https://docs.python.org/3/library/stdtypes.html#str.splitlines
335
+ NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029"
336
+
337
+ # We always push a trailing `\r` into the next decode iteration.
338
+ if self.trailing_cr:
339
+ text = "\r" + text
340
+ self.trailing_cr = False
341
+ if text.endswith("\r"):
342
+ self.trailing_cr = True
343
+ text = text[:-1]
344
+
345
+ if not text:
346
+ # NOTE: the edge case input of empty text doesn't occur in practice,
347
+ # because other httpx internals filter out this value
348
+ return [] # pragma: no cover
349
+
350
+ trailing_newline = text[-1] in NEWLINE_CHARS
351
+ lines = text.splitlines()
352
+
353
+ if len(lines) == 1 and not trailing_newline:
354
+ # No new lines, buffer the input and continue.
355
+ self.buffer.append(lines[0])
356
+ return []
357
+
358
+ if self.buffer:
359
+ # Include any existing buffer in the first portion of the
360
+ # splitlines result.
361
+ lines = ["".join(self.buffer) + lines[0]] + lines[1:]
362
+ self.buffer = []
363
+
364
+ if not trailing_newline:
365
+ # If the last segment of splitlines is not newline terminated,
366
+ # then drop it from our output and start a new buffer.
367
+ self.buffer = [lines.pop()]
368
+
369
+ return lines
370
+
371
+ def flush(self) -> list[str]:
372
+ if not self.buffer and not self.trailing_cr:
373
+ return []
374
+
375
+ lines = ["".join(self.buffer)]
376
+ self.buffer = []
377
+ self.trailing_cr = False
378
+ return lines
379
+
380
+
381
+ SUPPORTED_DECODERS = {
382
+ "identity": IdentityDecoder,
383
+ "gzip": GZipDecoder,
384
+ "deflate": DeflateDecoder,
385
+ "br": BrotliDecoder,
386
+ "zstd": ZStandardDecoder,
387
+ }
388
+
389
+
390
+ if brotli is None:
391
+ SUPPORTED_DECODERS.pop("br") # pragma: no cover
392
+ if zstandard is None:
393
+ SUPPORTED_DECODERS.pop("zstd") # pragma: no cover
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_exceptions.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Our exception hierarchy:
3
+
4
+ * HTTPError
5
+ x RequestError
6
+ + TransportError
7
+ - TimeoutException
8
+ · ConnectTimeout
9
+ · ReadTimeout
10
+ · WriteTimeout
11
+ · PoolTimeout
12
+ - NetworkError
13
+ · ConnectError
14
+ · ReadError
15
+ · WriteError
16
+ · CloseError
17
+ - ProtocolError
18
+ · LocalProtocolError
19
+ · RemoteProtocolError
20
+ - ProxyError
21
+ - UnsupportedProtocol
22
+ + DecodingError
23
+ + TooManyRedirects
24
+ x HTTPStatusError
25
+ * InvalidURL
26
+ * CookieConflict
27
+ * StreamError
28
+ x StreamConsumed
29
+ x StreamClosed
30
+ x ResponseNotRead
31
+ x RequestNotRead
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import contextlib
37
+ import typing
38
+
39
+ if typing.TYPE_CHECKING:
40
+ from ._models import Request, Response # pragma: no cover
41
+
42
+ __all__ = [
43
+ "CloseError",
44
+ "ConnectError",
45
+ "ConnectTimeout",
46
+ "CookieConflict",
47
+ "DecodingError",
48
+ "HTTPError",
49
+ "HTTPStatusError",
50
+ "InvalidURL",
51
+ "LocalProtocolError",
52
+ "NetworkError",
53
+ "PoolTimeout",
54
+ "ProtocolError",
55
+ "ProxyError",
56
+ "ReadError",
57
+ "ReadTimeout",
58
+ "RemoteProtocolError",
59
+ "RequestError",
60
+ "RequestNotRead",
61
+ "ResponseNotRead",
62
+ "StreamClosed",
63
+ "StreamConsumed",
64
+ "StreamError",
65
+ "TimeoutException",
66
+ "TooManyRedirects",
67
+ "TransportError",
68
+ "UnsupportedProtocol",
69
+ "WriteError",
70
+ "WriteTimeout",
71
+ ]
72
+
73
+
74
+ class HTTPError(Exception):
75
+ """
76
+ Base class for `RequestError` and `HTTPStatusError`.
77
+
78
+ Useful for `try...except` blocks when issuing a request,
79
+ and then calling `.raise_for_status()`.
80
+
81
+ For example:
82
+
83
+ ```
84
+ try:
85
+ response = httpx.get("https://www.example.com")
86
+ response.raise_for_status()
87
+ except httpx.HTTPError as exc:
88
+ print(f"HTTP Exception for {exc.request.url} - {exc}")
89
+ ```
90
+ """
91
+
92
+ def __init__(self, message: str) -> None:
93
+ super().__init__(message)
94
+ self._request: Request | None = None
95
+
96
+ @property
97
+ def request(self) -> Request:
98
+ if self._request is None:
99
+ raise RuntimeError("The .request property has not been set.")
100
+ return self._request
101
+
102
+ @request.setter
103
+ def request(self, request: Request) -> None:
104
+ self._request = request
105
+
106
+
107
+ class RequestError(HTTPError):
108
+ """
109
+ Base class for all exceptions that may occur when issuing a `.request()`.
110
+ """
111
+
112
+ def __init__(self, message: str, *, request: Request | None = None) -> None:
113
+ super().__init__(message)
114
+ # At the point an exception is raised we won't typically have a request
115
+ # instance to associate it with.
116
+ #
117
+ # The 'request_context' context manager is used within the Client and
118
+ # Response methods in order to ensure that any raised exceptions
119
+ # have a `.request` property set on them.
120
+ self._request = request
121
+
122
+
123
+ class TransportError(RequestError):
124
+ """
125
+ Base class for all exceptions that occur at the level of the Transport API.
126
+ """
127
+
128
+
129
+ # Timeout exceptions...
130
+
131
+
132
+ class TimeoutException(TransportError):
133
+ """
134
+ The base class for timeout errors.
135
+
136
+ An operation has timed out.
137
+ """
138
+
139
+
140
+ class ConnectTimeout(TimeoutException):
141
+ """
142
+ Timed out while connecting to the host.
143
+ """
144
+
145
+
146
+ class ReadTimeout(TimeoutException):
147
+ """
148
+ Timed out while receiving data from the host.
149
+ """
150
+
151
+
152
+ class WriteTimeout(TimeoutException):
153
+ """
154
+ Timed out while sending data to the host.
155
+ """
156
+
157
+
158
+ class PoolTimeout(TimeoutException):
159
+ """
160
+ Timed out waiting to acquire a connection from the pool.
161
+ """
162
+
163
+
164
+ # Core networking exceptions...
165
+
166
+
167
+ class NetworkError(TransportError):
168
+ """
169
+ The base class for network-related errors.
170
+
171
+ An error occurred while interacting with the network.
172
+ """
173
+
174
+
175
+ class ReadError(NetworkError):
176
+ """
177
+ Failed to receive data from the network.
178
+ """
179
+
180
+
181
+ class WriteError(NetworkError):
182
+ """
183
+ Failed to send data through the network.
184
+ """
185
+
186
+
187
+ class ConnectError(NetworkError):
188
+ """
189
+ Failed to establish a connection.
190
+ """
191
+
192
+
193
+ class CloseError(NetworkError):
194
+ """
195
+ Failed to close a connection.
196
+ """
197
+
198
+
199
+ # Other transport exceptions...
200
+
201
+
202
+ class ProxyError(TransportError):
203
+ """
204
+ An error occurred while establishing a proxy connection.
205
+ """
206
+
207
+
208
+ class UnsupportedProtocol(TransportError):
209
+ """
210
+ Attempted to make a request to an unsupported protocol.
211
+
212
+ For example issuing a request to `ftp://www.example.com`.
213
+ """
214
+
215
+
216
+ class ProtocolError(TransportError):
217
+ """
218
+ The protocol was violated.
219
+ """
220
+
221
+
222
+ class LocalProtocolError(ProtocolError):
223
+ """
224
+ A protocol was violated by the client.
225
+
226
+ For example if the user instantiated a `Request` instance explicitly,
227
+ failed to include the mandatory `Host:` header, and then issued it directly
228
+ using `client.send()`.
229
+ """
230
+
231
+
232
+ class RemoteProtocolError(ProtocolError):
233
+ """
234
+ The protocol was violated by the server.
235
+
236
+ For example, returning malformed HTTP.
237
+ """
238
+
239
+
240
+ # Other request exceptions...
241
+
242
+
243
+ class DecodingError(RequestError):
244
+ """
245
+ Decoding of the response failed, due to a malformed encoding.
246
+ """
247
+
248
+
249
+ class TooManyRedirects(RequestError):
250
+ """
251
+ Too many redirects.
252
+ """
253
+
254
+
255
+ # Client errors
256
+
257
+
258
+ class HTTPStatusError(HTTPError):
259
+ """
260
+ The response had an error HTTP status of 4xx or 5xx.
261
+
262
+ May be raised when calling `response.raise_for_status()`
263
+ """
264
+
265
+ def __init__(self, message: str, *, request: Request, response: Response) -> None:
266
+ super().__init__(message)
267
+ self.request = request
268
+ self.response = response
269
+
270
+
271
+ class InvalidURL(Exception):
272
+ """
273
+ URL is improperly formed or cannot be parsed.
274
+ """
275
+
276
+ def __init__(self, message: str) -> None:
277
+ super().__init__(message)
278
+
279
+
280
+ class CookieConflict(Exception):
281
+ """
282
+ Attempted to lookup a cookie by name, but multiple cookies existed.
283
+
284
+ Can occur when calling `response.cookies.get(...)`.
285
+ """
286
+
287
+ def __init__(self, message: str) -> None:
288
+ super().__init__(message)
289
+
290
+
291
+ # Stream exceptions...
292
+
293
+ # These may occur as the result of a programming error, by accessing
294
+ # the request/response stream in an invalid manner.
295
+
296
+
297
+ class StreamError(RuntimeError):
298
+ """
299
+ The base class for stream exceptions.
300
+
301
+ The developer made an error in accessing the request stream in
302
+ an invalid way.
303
+ """
304
+
305
+ def __init__(self, message: str) -> None:
306
+ super().__init__(message)
307
+
308
+
309
+ class StreamConsumed(StreamError):
310
+ """
311
+ Attempted to read or stream content, but the content has already
312
+ been streamed.
313
+ """
314
+
315
+ def __init__(self) -> None:
316
+ message = (
317
+ "Attempted to read or stream some content, but the content has "
318
+ "already been streamed. For requests, this could be due to passing "
319
+ "a generator as request content, and then receiving a redirect "
320
+ "response or a secondary request as part of an authentication flow."
321
+ "For responses, this could be due to attempting to stream the response "
322
+ "content more than once."
323
+ )
324
+ super().__init__(message)
325
+
326
+
327
+ class StreamClosed(StreamError):
328
+ """
329
+ Attempted to read or stream response content, but the request has been
330
+ closed.
331
+ """
332
+
333
+ def __init__(self) -> None:
334
+ message = (
335
+ "Attempted to read or stream content, but the stream has " "been closed."
336
+ )
337
+ super().__init__(message)
338
+
339
+
340
+ class ResponseNotRead(StreamError):
341
+ """
342
+ Attempted to access streaming response content, without having called `read()`.
343
+ """
344
+
345
+ def __init__(self) -> None:
346
+ message = (
347
+ "Attempted to access streaming response content,"
348
+ " without having called `read()`."
349
+ )
350
+ super().__init__(message)
351
+
352
+
353
+ class RequestNotRead(StreamError):
354
+ """
355
+ Attempted to access streaming request content, without having called `read()`.
356
+ """
357
+
358
+ def __init__(self) -> None:
359
+ message = (
360
+ "Attempted to access streaming request content,"
361
+ " without having called `read()`."
362
+ )
363
+ super().__init__(message)
364
+
365
+
366
+ @contextlib.contextmanager
367
+ def request_context(
368
+ request: Request | None = None,
369
+ ) -> typing.Iterator[None]:
370
+ """
371
+ A context manager that can be used to attach the given request context
372
+ to any `RequestError` exceptions that are raised within the block.
373
+ """
374
+ try:
375
+ yield
376
+ except RequestError as exc:
377
+ if request is not None:
378
+ exc.request = request
379
+ raise exc
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_main.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import json
5
+ import sys
6
+ import typing
7
+
8
+ import click
9
+ import pygments.lexers
10
+ import pygments.util
11
+ import rich.console
12
+ import rich.markup
13
+ import rich.progress
14
+ import rich.syntax
15
+ import rich.table
16
+
17
+ from ._client import Client
18
+ from ._exceptions import RequestError
19
+ from ._models import Response
20
+ from ._status_codes import codes
21
+
22
+ if typing.TYPE_CHECKING:
23
+ import httpcore # pragma: no cover
24
+
25
+
26
+ def print_help() -> None:
27
+ console = rich.console.Console()
28
+
29
+ console.print("[bold]HTTPX :butterfly:", justify="center")
30
+ console.print()
31
+ console.print("A next generation HTTP client.", justify="center")
32
+ console.print()
33
+ console.print(
34
+ "Usage: [bold]httpx[/bold] [cyan]<URL> [OPTIONS][/cyan] ", justify="left"
35
+ )
36
+ console.print()
37
+
38
+ table = rich.table.Table.grid(padding=1, pad_edge=True)
39
+ table.add_column("Parameter", no_wrap=True, justify="left", style="bold")
40
+ table.add_column("Description")
41
+ table.add_row(
42
+ "-m, --method [cyan]METHOD",
43
+ "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n"
44
+ "[Default: GET, or POST if a request body is included]",
45
+ )
46
+ table.add_row(
47
+ "-p, --params [cyan]<NAME VALUE> ...",
48
+ "Query parameters to include in the request URL.",
49
+ )
50
+ table.add_row(
51
+ "-c, --content [cyan]TEXT", "Byte content to include in the request body."
52
+ )
53
+ table.add_row(
54
+ "-d, --data [cyan]<NAME VALUE> ...", "Form data to include in the request body."
55
+ )
56
+ table.add_row(
57
+ "-f, --files [cyan]<NAME FILENAME> ...",
58
+ "Form files to include in the request body.",
59
+ )
60
+ table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.")
61
+ table.add_row(
62
+ "-h, --headers [cyan]<NAME VALUE> ...",
63
+ "Include additional HTTP headers in the request.",
64
+ )
65
+ table.add_row(
66
+ "--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request."
67
+ )
68
+ table.add_row(
69
+ "--auth [cyan]<USER PASS>",
70
+ "Username and password to include in the request. Specify '-' for the password"
71
+ " to use a password prompt. Note that using --verbose/-v will expose"
72
+ " the Authorization header, including the password encoding"
73
+ " in a trivially reversible format.",
74
+ )
75
+
76
+ table.add_row(
77
+ "--proxy [cyan]URL",
78
+ "Send the request via a proxy. Should be the URL giving the proxy address.",
79
+ )
80
+
81
+ table.add_row(
82
+ "--timeout [cyan]FLOAT",
83
+ "Timeout value to use for network operations, such as establishing the"
84
+ " connection, reading some data, etc... [Default: 5.0]",
85
+ )
86
+
87
+ table.add_row("--follow-redirects", "Automatically follow redirects.")
88
+ table.add_row("--no-verify", "Disable SSL verification.")
89
+ table.add_row(
90
+ "--http2", "Send the request using HTTP/2, if the remote server supports it."
91
+ )
92
+
93
+ table.add_row(
94
+ "--download [cyan]FILE",
95
+ "Save the response content as a file, rather than displaying it.",
96
+ )
97
+
98
+ table.add_row("-v, --verbose", "Verbose output. Show request as well as response.")
99
+ table.add_row("--help", "Show this message and exit.")
100
+ console.print(table)
101
+
102
+
103
+ def get_lexer_for_response(response: Response) -> str:
104
+ content_type = response.headers.get("Content-Type")
105
+ if content_type is not None:
106
+ mime_type, _, _ = content_type.partition(";")
107
+ try:
108
+ return typing.cast(
109
+ str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name
110
+ )
111
+ except pygments.util.ClassNotFound: # pragma: no cover
112
+ pass
113
+ return "" # pragma: no cover
114
+
115
+
116
+ def format_request_headers(request: httpcore.Request, http2: bool = False) -> str:
117
+ version = "HTTP/2" if http2 else "HTTP/1.1"
118
+ headers = [
119
+ (name.lower() if http2 else name, value) for name, value in request.headers
120
+ ]
121
+ method = request.method.decode("ascii")
122
+ target = request.url.target.decode("ascii")
123
+ lines = [f"{method} {target} {version}"] + [
124
+ f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers
125
+ ]
126
+ return "\n".join(lines)
127
+
128
+
129
+ def format_response_headers(
130
+ http_version: bytes,
131
+ status: int,
132
+ reason_phrase: bytes | None,
133
+ headers: list[tuple[bytes, bytes]],
134
+ ) -> str:
135
+ version = http_version.decode("ascii")
136
+ reason = (
137
+ codes.get_reason_phrase(status)
138
+ if reason_phrase is None
139
+ else reason_phrase.decode("ascii")
140
+ )
141
+ lines = [f"{version} {status} {reason}"] + [
142
+ f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers
143
+ ]
144
+ return "\n".join(lines)
145
+
146
+
147
+ def print_request_headers(request: httpcore.Request, http2: bool = False) -> None:
148
+ console = rich.console.Console()
149
+ http_text = format_request_headers(request, http2=http2)
150
+ syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
151
+ console.print(syntax)
152
+ syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)
153
+ console.print(syntax)
154
+
155
+
156
+ def print_response_headers(
157
+ http_version: bytes,
158
+ status: int,
159
+ reason_phrase: bytes | None,
160
+ headers: list[tuple[bytes, bytes]],
161
+ ) -> None:
162
+ console = rich.console.Console()
163
+ http_text = format_response_headers(http_version, status, reason_phrase, headers)
164
+ syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
165
+ console.print(syntax)
166
+ syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)
167
+ console.print(syntax)
168
+
169
+
170
+ def print_response(response: Response) -> None:
171
+ console = rich.console.Console()
172
+ lexer_name = get_lexer_for_response(response)
173
+ if lexer_name:
174
+ if lexer_name.lower() == "json":
175
+ try:
176
+ data = response.json()
177
+ text = json.dumps(data, indent=4)
178
+ except ValueError: # pragma: no cover
179
+ text = response.text
180
+ else:
181
+ text = response.text
182
+
183
+ syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True)
184
+ console.print(syntax)
185
+ else:
186
+ console.print(f"<{len(response.content)} bytes of binary data>")
187
+
188
+
189
+ _PCTRTT = typing.Tuple[typing.Tuple[str, str], ...]
190
+ _PCTRTTT = typing.Tuple[_PCTRTT, ...]
191
+ _PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]]
192
+
193
+
194
+ def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover
195
+ lines = []
196
+ for key, value in cert.items():
197
+ if isinstance(value, (list, tuple)):
198
+ lines.append(f"* {key}:")
199
+ for item in value:
200
+ if key in ("subject", "issuer"):
201
+ for sub_item in item:
202
+ lines.append(f"* {sub_item[0]}: {sub_item[1]!r}")
203
+ elif isinstance(item, tuple) and len(item) == 2:
204
+ lines.append(f"* {item[0]}: {item[1]!r}")
205
+ else:
206
+ lines.append(f"* {item!r}")
207
+ else:
208
+ lines.append(f"* {key}: {value!r}")
209
+ return "\n".join(lines)
210
+
211
+
212
+ def trace(
213
+ name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False
214
+ ) -> None:
215
+ console = rich.console.Console()
216
+ if name == "connection.connect_tcp.started" and verbose:
217
+ host = info["host"]
218
+ console.print(f"* Connecting to {host!r}")
219
+ elif name == "connection.connect_tcp.complete" and verbose:
220
+ stream = info["return_value"]
221
+ server_addr = stream.get_extra_info("server_addr")
222
+ console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}")
223
+ elif name == "connection.start_tls.complete" and verbose: # pragma: no cover
224
+ stream = info["return_value"]
225
+ ssl_object = stream.get_extra_info("ssl_object")
226
+ version = ssl_object.version()
227
+ cipher = ssl_object.cipher()
228
+ server_cert = ssl_object.getpeercert()
229
+ alpn = ssl_object.selected_alpn_protocol()
230
+ console.print(f"* SSL established using {version!r} / {cipher[0]!r}")
231
+ console.print(f"* Selected ALPN protocol: {alpn!r}")
232
+ if server_cert:
233
+ console.print("* Server certificate:")
234
+ console.print(format_certificate(server_cert))
235
+ elif name == "http11.send_request_headers.started" and verbose:
236
+ request = info["request"]
237
+ print_request_headers(request, http2=False)
238
+ elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover
239
+ request = info["request"]
240
+ print_request_headers(request, http2=True)
241
+ elif name == "http11.receive_response_headers.complete":
242
+ http_version, status, reason_phrase, headers = info["return_value"]
243
+ print_response_headers(http_version, status, reason_phrase, headers)
244
+ elif name == "http2.receive_response_headers.complete": # pragma: no cover
245
+ status, headers = info["return_value"]
246
+ http_version = b"HTTP/2"
247
+ reason_phrase = None
248
+ print_response_headers(http_version, status, reason_phrase, headers)
249
+
250
+
251
+ def download_response(response: Response, download: typing.BinaryIO) -> None:
252
+ console = rich.console.Console()
253
+ console.print()
254
+ content_length = response.headers.get("Content-Length")
255
+ with rich.progress.Progress(
256
+ "[progress.description]{task.description}",
257
+ "[progress.percentage]{task.percentage:>3.0f}%",
258
+ rich.progress.BarColumn(bar_width=None),
259
+ rich.progress.DownloadColumn(),
260
+ rich.progress.TransferSpeedColumn(),
261
+ ) as progress:
262
+ description = f"Downloading [bold]{rich.markup.escape(download.name)}"
263
+ download_task = progress.add_task(
264
+ description,
265
+ total=int(content_length or 0),
266
+ start=content_length is not None,
267
+ )
268
+ for chunk in response.iter_bytes():
269
+ download.write(chunk)
270
+ progress.update(download_task, completed=response.num_bytes_downloaded)
271
+
272
+
273
+ def validate_json(
274
+ ctx: click.Context,
275
+ param: click.Option | click.Parameter,
276
+ value: typing.Any,
277
+ ) -> typing.Any:
278
+ if value is None:
279
+ return None
280
+
281
+ try:
282
+ return json.loads(value)
283
+ except json.JSONDecodeError: # pragma: no cover
284
+ raise click.BadParameter("Not valid JSON")
285
+
286
+
287
+ def validate_auth(
288
+ ctx: click.Context,
289
+ param: click.Option | click.Parameter,
290
+ value: typing.Any,
291
+ ) -> typing.Any:
292
+ if value == (None, None):
293
+ return None
294
+
295
+ username, password = value
296
+ if password == "-": # pragma: no cover
297
+ password = click.prompt("Password", hide_input=True)
298
+ return (username, password)
299
+
300
+
301
+ def handle_help(
302
+ ctx: click.Context,
303
+ param: click.Option | click.Parameter,
304
+ value: typing.Any,
305
+ ) -> None:
306
+ if not value or ctx.resilient_parsing:
307
+ return
308
+
309
+ print_help()
310
+ ctx.exit()
311
+
312
+
313
+ @click.command(add_help_option=False)
314
+ @click.argument("url", type=str)
315
+ @click.option(
316
+ "--method",
317
+ "-m",
318
+ "method",
319
+ type=str,
320
+ help=(
321
+ "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. "
322
+ "[Default: GET, or POST if a request body is included]"
323
+ ),
324
+ )
325
+ @click.option(
326
+ "--params",
327
+ "-p",
328
+ "params",
329
+ type=(str, str),
330
+ multiple=True,
331
+ help="Query parameters to include in the request URL.",
332
+ )
333
+ @click.option(
334
+ "--content",
335
+ "-c",
336
+ "content",
337
+ type=str,
338
+ help="Byte content to include in the request body.",
339
+ )
340
+ @click.option(
341
+ "--data",
342
+ "-d",
343
+ "data",
344
+ type=(str, str),
345
+ multiple=True,
346
+ help="Form data to include in the request body.",
347
+ )
348
+ @click.option(
349
+ "--files",
350
+ "-f",
351
+ "files",
352
+ type=(str, click.File(mode="rb")),
353
+ multiple=True,
354
+ help="Form files to include in the request body.",
355
+ )
356
+ @click.option(
357
+ "--json",
358
+ "-j",
359
+ "json",
360
+ type=str,
361
+ callback=validate_json,
362
+ help="JSON data to include in the request body.",
363
+ )
364
+ @click.option(
365
+ "--headers",
366
+ "-h",
367
+ "headers",
368
+ type=(str, str),
369
+ multiple=True,
370
+ help="Include additional HTTP headers in the request.",
371
+ )
372
+ @click.option(
373
+ "--cookies",
374
+ "cookies",
375
+ type=(str, str),
376
+ multiple=True,
377
+ help="Cookies to include in the request.",
378
+ )
379
+ @click.option(
380
+ "--auth",
381
+ "auth",
382
+ type=(str, str),
383
+ default=(None, None),
384
+ callback=validate_auth,
385
+ help=(
386
+ "Username and password to include in the request. "
387
+ "Specify '-' for the password to use a password prompt. "
388
+ "Note that using --verbose/-v will expose the Authorization header, "
389
+ "including the password encoding in a trivially reversible format."
390
+ ),
391
+ )
392
+ @click.option(
393
+ "--proxy",
394
+ "proxy",
395
+ type=str,
396
+ default=None,
397
+ help="Send the request via a proxy. Should be the URL giving the proxy address.",
398
+ )
399
+ @click.option(
400
+ "--timeout",
401
+ "timeout",
402
+ type=float,
403
+ default=5.0,
404
+ help=(
405
+ "Timeout value to use for network operations, such as establishing the "
406
+ "connection, reading some data, etc... [Default: 5.0]"
407
+ ),
408
+ )
409
+ @click.option(
410
+ "--follow-redirects",
411
+ "follow_redirects",
412
+ is_flag=True,
413
+ default=False,
414
+ help="Automatically follow redirects.",
415
+ )
416
+ @click.option(
417
+ "--no-verify",
418
+ "verify",
419
+ is_flag=True,
420
+ default=True,
421
+ help="Disable SSL verification.",
422
+ )
423
+ @click.option(
424
+ "--http2",
425
+ "http2",
426
+ type=bool,
427
+ is_flag=True,
428
+ default=False,
429
+ help="Send the request using HTTP/2, if the remote server supports it.",
430
+ )
431
+ @click.option(
432
+ "--download",
433
+ type=click.File("wb"),
434
+ help="Save the response content as a file, rather than displaying it.",
435
+ )
436
+ @click.option(
437
+ "--verbose",
438
+ "-v",
439
+ type=bool,
440
+ is_flag=True,
441
+ default=False,
442
+ help="Verbose. Show request as well as response.",
443
+ )
444
+ @click.option(
445
+ "--help",
446
+ is_flag=True,
447
+ is_eager=True,
448
+ expose_value=False,
449
+ callback=handle_help,
450
+ help="Show this message and exit.",
451
+ )
452
+ def main(
453
+ url: str,
454
+ method: str,
455
+ params: list[tuple[str, str]],
456
+ content: str,
457
+ data: list[tuple[str, str]],
458
+ files: list[tuple[str, click.File]],
459
+ json: str,
460
+ headers: list[tuple[str, str]],
461
+ cookies: list[tuple[str, str]],
462
+ auth: tuple[str, str] | None,
463
+ proxy: str,
464
+ timeout: float,
465
+ follow_redirects: bool,
466
+ verify: bool,
467
+ http2: bool,
468
+ download: typing.BinaryIO | None,
469
+ verbose: bool,
470
+ ) -> None:
471
+ """
472
+ An HTTP command line client.
473
+ Sends a request and displays the response.
474
+ """
475
+ if not method:
476
+ method = "POST" if content or data or files or json else "GET"
477
+
478
+ try:
479
+ with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client:
480
+ with client.stream(
481
+ method,
482
+ url,
483
+ params=list(params),
484
+ content=content,
485
+ data=dict(data),
486
+ files=files, # type: ignore
487
+ json=json,
488
+ headers=headers,
489
+ cookies=dict(cookies),
490
+ auth=auth,
491
+ follow_redirects=follow_redirects,
492
+ extensions={"trace": functools.partial(trace, verbose=verbose)},
493
+ ) as response:
494
+ if download is not None:
495
+ download_response(response, download)
496
+ else:
497
+ response.read()
498
+ if response.content:
499
+ print_response(response)
500
+
501
+ except RequestError as exc:
502
+ console = rich.console.Console()
503
+ console.print(f"[red]{type(exc).__name__}[/red]: {exc}")
504
+ sys.exit(1)
505
+
506
+ sys.exit(0 if response.is_success else 1)
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_multipart.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import mimetypes
5
+ import os
6
+ import re
7
+ import typing
8
+ from pathlib import Path
9
+
10
+ from ._types import (
11
+ AsyncByteStream,
12
+ FileContent,
13
+ FileTypes,
14
+ RequestData,
15
+ RequestFiles,
16
+ SyncByteStream,
17
+ )
18
+ from ._utils import (
19
+ peek_filelike_length,
20
+ primitive_value_to_str,
21
+ to_bytes,
22
+ )
23
+
24
+ _HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}
25
+ _HTML5_FORM_ENCODING_REPLACEMENTS.update(
26
+ {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}
27
+ )
28
+ _HTML5_FORM_ENCODING_RE = re.compile(
29
+ r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])
30
+ )
31
+
32
+
33
+ def _format_form_param(name: str, value: str) -> bytes:
34
+ """
35
+ Encode a name/value pair within a multipart form.
36
+ """
37
+
38
+ def replacer(match: typing.Match[str]) -> str:
39
+ return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]
40
+
41
+ value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)
42
+ return f'{name}="{value}"'.encode()
43
+
44
+
45
+ def _guess_content_type(filename: str | None) -> str | None:
46
+ """
47
+ Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.
48
+
49
+ Returns `None` if `filename` is `None` or empty.
50
+ """
51
+ if filename:
52
+ return mimetypes.guess_type(filename)[0] or "application/octet-stream"
53
+ return None
54
+
55
+
56
+ def get_multipart_boundary_from_content_type(
57
+ content_type: bytes | None,
58
+ ) -> bytes | None:
59
+ if not content_type or not content_type.startswith(b"multipart/form-data"):
60
+ return None
61
+ # parse boundary according to
62
+ # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
63
+ if b";" in content_type:
64
+ for section in content_type.split(b";"):
65
+ if section.strip().lower().startswith(b"boundary="):
66
+ return section.strip()[len(b"boundary=") :].strip(b'"')
67
+ return None
68
+
69
+
70
+ class DataField:
71
+ """
72
+ A single form field item, within a multipart form field.
73
+ """
74
+
75
+ def __init__(self, name: str, value: str | bytes | int | float | None) -> None:
76
+ if not isinstance(name, str):
77
+ raise TypeError(
78
+ f"Invalid type for name. Expected str, got {type(name)}: {name!r}"
79
+ )
80
+ if value is not None and not isinstance(value, (str, bytes, int, float)):
81
+ raise TypeError(
82
+ "Invalid type for value. Expected primitive type,"
83
+ f" got {type(value)}: {value!r}"
84
+ )
85
+ self.name = name
86
+ self.value: str | bytes = (
87
+ value if isinstance(value, bytes) else primitive_value_to_str(value)
88
+ )
89
+
90
+ def render_headers(self) -> bytes:
91
+ if not hasattr(self, "_headers"):
92
+ name = _format_form_param("name", self.name)
93
+ self._headers = b"".join(
94
+ [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]
95
+ )
96
+
97
+ return self._headers
98
+
99
+ def render_data(self) -> bytes:
100
+ if not hasattr(self, "_data"):
101
+ self._data = to_bytes(self.value)
102
+
103
+ return self._data
104
+
105
+ def get_length(self) -> int:
106
+ headers = self.render_headers()
107
+ data = self.render_data()
108
+ return len(headers) + len(data)
109
+
110
+ def render(self) -> typing.Iterator[bytes]:
111
+ yield self.render_headers()
112
+ yield self.render_data()
113
+
114
+
115
+ class FileField:
116
+ """
117
+ A single file field item, within a multipart form field.
118
+ """
119
+
120
+ CHUNK_SIZE = 64 * 1024
121
+
122
+ def __init__(self, name: str, value: FileTypes) -> None:
123
+ self.name = name
124
+
125
+ fileobj: FileContent
126
+
127
+ headers: dict[str, str] = {}
128
+ content_type: str | None = None
129
+
130
+ # This large tuple based API largely mirror's requests' API
131
+ # It would be good to think of better APIs for this that we could
132
+ # include in httpx 2.0 since variable length tuples(especially of 4 elements)
133
+ # are quite unwieldly
134
+ if isinstance(value, tuple):
135
+ if len(value) == 2:
136
+ # neither the 3rd parameter (content_type) nor the 4th (headers)
137
+ # was included
138
+ filename, fileobj = value
139
+ elif len(value) == 3:
140
+ filename, fileobj, content_type = value
141
+ else:
142
+ # all 4 parameters included
143
+ filename, fileobj, content_type, headers = value # type: ignore
144
+ else:
145
+ filename = Path(str(getattr(value, "name", "upload"))).name
146
+ fileobj = value
147
+
148
+ if content_type is None:
149
+ content_type = _guess_content_type(filename)
150
+
151
+ has_content_type_header = any("content-type" in key.lower() for key in headers)
152
+ if content_type is not None and not has_content_type_header:
153
+ # note that unlike requests, we ignore the content_type provided in the 3rd
154
+ # tuple element if it is also included in the headers requests does
155
+ # the opposite (it overwrites the headerwith the 3rd tuple element)
156
+ headers["Content-Type"] = content_type
157
+
158
+ if isinstance(fileobj, io.StringIO):
159
+ raise TypeError(
160
+ "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'."
161
+ )
162
+ if isinstance(fileobj, io.TextIOBase):
163
+ raise TypeError(
164
+ "Multipart file uploads must be opened in binary mode, not text mode."
165
+ )
166
+
167
+ self.filename = filename
168
+ self.file = fileobj
169
+ self.headers = headers
170
+
171
+ def get_length(self) -> int | None:
172
+ headers = self.render_headers()
173
+
174
+ if isinstance(self.file, (str, bytes)):
175
+ return len(headers) + len(to_bytes(self.file))
176
+
177
+ file_length = peek_filelike_length(self.file)
178
+
179
+ # If we can't determine the filesize without reading it into memory,
180
+ # then return `None` here, to indicate an unknown file length.
181
+ if file_length is None:
182
+ return None
183
+
184
+ return len(headers) + file_length
185
+
186
+ def render_headers(self) -> bytes:
187
+ if not hasattr(self, "_headers"):
188
+ parts = [
189
+ b"Content-Disposition: form-data; ",
190
+ _format_form_param("name", self.name),
191
+ ]
192
+ if self.filename:
193
+ filename = _format_form_param("filename", self.filename)
194
+ parts.extend([b"; ", filename])
195
+ for header_name, header_value in self.headers.items():
196
+ key, val = f"\r\n{header_name}: ".encode(), header_value.encode()
197
+ parts.extend([key, val])
198
+ parts.append(b"\r\n\r\n")
199
+ self._headers = b"".join(parts)
200
+
201
+ return self._headers
202
+
203
+ def render_data(self) -> typing.Iterator[bytes]:
204
+ if isinstance(self.file, (str, bytes)):
205
+ yield to_bytes(self.file)
206
+ return
207
+
208
+ if hasattr(self.file, "seek"):
209
+ try:
210
+ self.file.seek(0)
211
+ except io.UnsupportedOperation:
212
+ pass
213
+
214
+ chunk = self.file.read(self.CHUNK_SIZE)
215
+ while chunk:
216
+ yield to_bytes(chunk)
217
+ chunk = self.file.read(self.CHUNK_SIZE)
218
+
219
+ def render(self) -> typing.Iterator[bytes]:
220
+ yield self.render_headers()
221
+ yield from self.render_data()
222
+
223
+
224
+ class MultipartStream(SyncByteStream, AsyncByteStream):
225
+ """
226
+ Request content as streaming multipart encoded form data.
227
+ """
228
+
229
+ def __init__(
230
+ self,
231
+ data: RequestData,
232
+ files: RequestFiles,
233
+ boundary: bytes | None = None,
234
+ ) -> None:
235
+ if boundary is None:
236
+ boundary = os.urandom(16).hex().encode("ascii")
237
+
238
+ self.boundary = boundary
239
+ self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(
240
+ "ascii"
241
+ )
242
+ self.fields = list(self._iter_fields(data, files))
243
+
244
+ def _iter_fields(
245
+ self, data: RequestData, files: RequestFiles
246
+ ) -> typing.Iterator[FileField | DataField]:
247
+ for name, value in data.items():
248
+ if isinstance(value, (tuple, list)):
249
+ for item in value:
250
+ yield DataField(name=name, value=item)
251
+ else:
252
+ yield DataField(name=name, value=value)
253
+
254
+ file_items = files.items() if isinstance(files, typing.Mapping) else files
255
+ for name, value in file_items:
256
+ yield FileField(name=name, value=value)
257
+
258
+ def iter_chunks(self) -> typing.Iterator[bytes]:
259
+ for field in self.fields:
260
+ yield b"--%s\r\n" % self.boundary
261
+ yield from field.render()
262
+ yield b"\r\n"
263
+ yield b"--%s--\r\n" % self.boundary
264
+
265
+ def get_content_length(self) -> int | None:
266
+ """
267
+ Return the length of the multipart encoded content, or `None` if
268
+ any of the files have a length that cannot be determined upfront.
269
+ """
270
+ boundary_length = len(self.boundary)
271
+ length = 0
272
+
273
+ for field in self.fields:
274
+ field_length = field.get_length()
275
+ if field_length is None:
276
+ return None
277
+
278
+ length += 2 + boundary_length + 2 # b"--{boundary}\r\n"
279
+ length += field_length
280
+ length += 2 # b"\r\n"
281
+
282
+ length += 2 + boundary_length + 4 # b"--{boundary}--\r\n"
283
+ return length
284
+
285
+ # Content stream interface.
286
+
287
+ def get_headers(self) -> dict[str, str]:
288
+ content_length = self.get_content_length()
289
+ content_type = self.content_type
290
+ if content_length is None:
291
+ return {"Transfer-Encoding": "chunked", "Content-Type": content_type}
292
+ return {"Content-Length": str(content_length), "Content-Type": content_type}
293
+
294
+ def __iter__(self) -> typing.Iterator[bytes]:
295
+ for chunk in self.iter_chunks():
296
+ yield chunk
297
+
298
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
299
+ for chunk in self.iter_chunks():
300
+ yield chunk
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_urls.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+ from urllib.parse import parse_qs, unquote, urlencode
5
+
6
+ import idna
7
+
8
+ from ._types import QueryParamTypes
9
+ from ._urlparse import urlparse
10
+ from ._utils import primitive_value_to_str
11
+
12
+ __all__ = ["URL", "QueryParams"]
13
+
14
+
15
+ class URL:
16
+ """
17
+ url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")
18
+
19
+ assert url.scheme == "https"
20
+ assert url.username == "jo@email.com"
21
+ assert url.password == "a secret"
22
+ assert url.userinfo == b"jo%40email.com:a%20secret"
23
+ assert url.host == "müller.de"
24
+ assert url.raw_host == b"xn--mller-kva.de"
25
+ assert url.port == 1234
26
+ assert url.netloc == b"xn--mller-kva.de:1234"
27
+ assert url.path == "/pa th"
28
+ assert url.query == b"?search=ab"
29
+ assert url.raw_path == b"/pa%20th?search=ab"
30
+ assert url.fragment == "anchorlink"
31
+
32
+ The components of a URL are broken down like this:
33
+
34
+ https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink
35
+ [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]
36
+ [ userinfo ] [ netloc ][ raw_path ]
37
+
38
+ Note that:
39
+
40
+ * `url.scheme` is normalized to always be lowercased.
41
+
42
+ * `url.host` is normalized to always be lowercased. Internationalized domain
43
+ names are represented in unicode, without IDNA encoding applied. For instance:
44
+
45
+ url = httpx.URL("http://中国.icom.museum")
46
+ assert url.host == "中国.icom.museum"
47
+ url = httpx.URL("http://xn--fiqs8s.icom.museum")
48
+ assert url.host == "中国.icom.museum"
49
+
50
+ * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.
51
+
52
+ url = httpx.URL("http://中国.icom.museum")
53
+ assert url.raw_host == b"xn--fiqs8s.icom.museum"
54
+ url = httpx.URL("http://xn--fiqs8s.icom.museum")
55
+ assert url.raw_host == b"xn--fiqs8s.icom.museum"
56
+
57
+ * `url.port` is either None or an integer. URLs that include the default port for
58
+ "http", "https", "ws", "wss", and "ftp" schemes have their port
59
+ normalized to `None`.
60
+
61
+ assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80")
62
+ assert httpx.URL("http://example.com").port is None
63
+ assert httpx.URL("http://example.com:80").port is None
64
+
65
+ * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work
66
+ with `url.username` and `url.password` instead, which handle the URL escaping.
67
+
68
+ * `url.raw_path` is raw bytes of both the path and query, without URL escaping.
69
+ This portion is used as the target when constructing HTTP requests. Usually you'll
70
+ want to work with `url.path` instead.
71
+
72
+ * `url.query` is raw bytes, without URL escaping. A URL query string portion can
73
+ only be properly URL escaped when decoding the parameter names and values
74
+ themselves.
75
+ """
76
+
77
+ def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None:
78
+ if kwargs:
79
+ allowed = {
80
+ "scheme": str,
81
+ "username": str,
82
+ "password": str,
83
+ "userinfo": bytes,
84
+ "host": str,
85
+ "port": int,
86
+ "netloc": bytes,
87
+ "path": str,
88
+ "query": bytes,
89
+ "raw_path": bytes,
90
+ "fragment": str,
91
+ "params": object,
92
+ }
93
+
94
+ # Perform type checking for all supported keyword arguments.
95
+ for key, value in kwargs.items():
96
+ if key not in allowed:
97
+ message = f"{key!r} is an invalid keyword argument for URL()"
98
+ raise TypeError(message)
99
+ if value is not None and not isinstance(value, allowed[key]):
100
+ expected = allowed[key].__name__
101
+ seen = type(value).__name__
102
+ message = f"Argument {key!r} must be {expected} but got {seen}"
103
+ raise TypeError(message)
104
+ if isinstance(value, bytes):
105
+ kwargs[key] = value.decode("ascii")
106
+
107
+ if "params" in kwargs:
108
+ # Replace any "params" keyword with the raw "query" instead.
109
+ #
110
+ # Ensure that empty params use `kwargs["query"] = None` rather
111
+ # than `kwargs["query"] = ""`, so that generated URLs do not
112
+ # include an empty trailing "?".
113
+ params = kwargs.pop("params")
114
+ kwargs["query"] = None if not params else str(QueryParams(params))
115
+
116
+ if isinstance(url, str):
117
+ self._uri_reference = urlparse(url, **kwargs)
118
+ elif isinstance(url, URL):
119
+ self._uri_reference = url._uri_reference.copy_with(**kwargs)
120
+ else:
121
+ raise TypeError(
122
+ "Invalid type for url. Expected str or httpx.URL,"
123
+ f" got {type(url)}: {url!r}"
124
+ )
125
+
126
+ @property
127
+ def scheme(self) -> str:
128
+ """
129
+ The URL scheme, such as "http", "https".
130
+ Always normalised to lowercase.
131
+ """
132
+ return self._uri_reference.scheme
133
+
134
+ @property
135
+ def raw_scheme(self) -> bytes:
136
+ """
137
+ The raw bytes representation of the URL scheme, such as b"http", b"https".
138
+ Always normalised to lowercase.
139
+ """
140
+ return self._uri_reference.scheme.encode("ascii")
141
+
142
+ @property
143
+ def userinfo(self) -> bytes:
144
+ """
145
+ The URL userinfo as a raw bytestring.
146
+ For example: b"jo%40email.com:a%20secret".
147
+ """
148
+ return self._uri_reference.userinfo.encode("ascii")
149
+
150
+ @property
151
+ def username(self) -> str:
152
+ """
153
+ The URL username as a string, with URL decoding applied.
154
+ For example: "jo@email.com"
155
+ """
156
+ userinfo = self._uri_reference.userinfo
157
+ return unquote(userinfo.partition(":")[0])
158
+
159
+ @property
160
+ def password(self) -> str:
161
+ """
162
+ The URL password as a string, with URL decoding applied.
163
+ For example: "a secret"
164
+ """
165
+ userinfo = self._uri_reference.userinfo
166
+ return unquote(userinfo.partition(":")[2])
167
+
168
+ @property
169
+ def host(self) -> str:
170
+ """
171
+ The URL host as a string.
172
+ Always normalized to lowercase, with IDNA hosts decoded into unicode.
173
+
174
+ Examples:
175
+
176
+ url = httpx.URL("http://www.EXAMPLE.org")
177
+ assert url.host == "www.example.org"
178
+
179
+ url = httpx.URL("http://中国.icom.museum")
180
+ assert url.host == "中国.icom.museum"
181
+
182
+ url = httpx.URL("http://xn--fiqs8s.icom.museum")
183
+ assert url.host == "中国.icom.museum"
184
+
185
+ url = httpx.URL("https://[::ffff:192.168.0.1]")
186
+ assert url.host == "::ffff:192.168.0.1"
187
+ """
188
+ host: str = self._uri_reference.host
189
+
190
+ if host.startswith("xn--"):
191
+ host = idna.decode(host)
192
+
193
+ return host
194
+
195
+ @property
196
+ def raw_host(self) -> bytes:
197
+ """
198
+ The raw bytes representation of the URL host.
199
+ Always normalized to lowercase, and IDNA encoded.
200
+
201
+ Examples:
202
+
203
+ url = httpx.URL("http://www.EXAMPLE.org")
204
+ assert url.raw_host == b"www.example.org"
205
+
206
+ url = httpx.URL("http://中国.icom.museum")
207
+ assert url.raw_host == b"xn--fiqs8s.icom.museum"
208
+
209
+ url = httpx.URL("http://xn--fiqs8s.icom.museum")
210
+ assert url.raw_host == b"xn--fiqs8s.icom.museum"
211
+
212
+ url = httpx.URL("https://[::ffff:192.168.0.1]")
213
+ assert url.raw_host == b"::ffff:192.168.0.1"
214
+ """
215
+ return self._uri_reference.host.encode("ascii")
216
+
217
+ @property
218
+ def port(self) -> int | None:
219
+ """
220
+ The URL port as an integer.
221
+
222
+ Note that the URL class performs port normalization as per the WHATWG spec.
223
+ Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always
224
+ treated as `None`.
225
+
226
+ For example:
227
+
228
+ assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80")
229
+ assert httpx.URL("http://www.example.com:80").port is None
230
+ """
231
+ return self._uri_reference.port
232
+
233
+ @property
234
+ def netloc(self) -> bytes:
235
+ """
236
+ Either `<host>` or `<host>:<port>` as bytes.
237
+ Always normalized to lowercase, and IDNA encoded.
238
+
239
+ This property may be used for generating the value of a request
240
+ "Host" header.
241
+ """
242
+ return self._uri_reference.netloc.encode("ascii")
243
+
244
+ @property
245
+ def path(self) -> str:
246
+ """
247
+ The URL path as a string. Excluding the query string, and URL decoded.
248
+
249
+ For example:
250
+
251
+ url = httpx.URL("https://example.com/pa%20th")
252
+ assert url.path == "/pa th"
253
+ """
254
+ path = self._uri_reference.path or "/"
255
+ return unquote(path)
256
+
257
+ @property
258
+ def query(self) -> bytes:
259
+ """
260
+ The URL query string, as raw bytes, excluding the leading b"?".
261
+
262
+ This is necessarily a bytewise interface, because we cannot
263
+ perform URL decoding of this representation until we've parsed
264
+ the keys and values into a QueryParams instance.
265
+
266
+ For example:
267
+
268
+ url = httpx.URL("https://example.com/?filter=some%20search%20terms")
269
+ assert url.query == b"filter=some%20search%20terms"
270
+ """
271
+ query = self._uri_reference.query or ""
272
+ return query.encode("ascii")
273
+
274
+ @property
275
+ def params(self) -> QueryParams:
276
+ """
277
+ The URL query parameters, neatly parsed and packaged into an immutable
278
+ multidict representation.
279
+ """
280
+ return QueryParams(self._uri_reference.query)
281
+
282
+ @property
283
+ def raw_path(self) -> bytes:
284
+ """
285
+ The complete URL path and query string as raw bytes.
286
+ Used as the target when constructing HTTP requests.
287
+
288
+ For example:
289
+
290
+ GET /users?search=some%20text HTTP/1.1
291
+ Host: www.example.org
292
+ Connection: close
293
+ """
294
+ path = self._uri_reference.path or "/"
295
+ if self._uri_reference.query is not None:
296
+ path += "?" + self._uri_reference.query
297
+ return path.encode("ascii")
298
+
299
+ @property
300
+ def fragment(self) -> str:
301
+ """
302
+ The URL fragments, as used in HTML anchors.
303
+ As a string, without the leading '#'.
304
+ """
305
+ return unquote(self._uri_reference.fragment or "")
306
+
307
+ @property
308
+ def is_absolute_url(self) -> bool:
309
+ """
310
+ Return `True` for absolute URLs such as 'http://example.com/path',
311
+ and `False` for relative URLs such as '/path'.
312
+ """
313
+ # We don't use `.is_absolute` from `rfc3986` because it treats
314
+ # URLs with a fragment portion as not absolute.
315
+ # What we actually care about is if the URL provides
316
+ # a scheme and hostname to which connections should be made.
317
+ return bool(self._uri_reference.scheme and self._uri_reference.host)
318
+
319
+ @property
320
+ def is_relative_url(self) -> bool:
321
+ """
322
+ Return `False` for absolute URLs such as 'http://example.com/path',
323
+ and `True` for relative URLs such as '/path'.
324
+ """
325
+ return not self.is_absolute_url
326
+
327
+ def copy_with(self, **kwargs: typing.Any) -> URL:
328
+ """
329
+ Copy this URL, returning a new URL with some components altered.
330
+ Accepts the same set of parameters as the components that are made
331
+ available via properties on the `URL` class.
332
+
333
+ For example:
334
+
335
+ url = httpx.URL("https://www.example.com").copy_with(
336
+ username="jo@gmail.com", password="a secret"
337
+ )
338
+ assert url == "https://jo%40email.com:a%20secret@www.example.com"
339
+ """
340
+ return URL(self, **kwargs)
341
+
342
+ def copy_set_param(self, key: str, value: typing.Any = None) -> URL:
343
+ return self.copy_with(params=self.params.set(key, value))
344
+
345
+ def copy_add_param(self, key: str, value: typing.Any = None) -> URL:
346
+ return self.copy_with(params=self.params.add(key, value))
347
+
348
+ def copy_remove_param(self, key: str) -> URL:
349
+ return self.copy_with(params=self.params.remove(key))
350
+
351
+ def copy_merge_params(self, params: QueryParamTypes) -> URL:
352
+ return self.copy_with(params=self.params.merge(params))
353
+
354
+ def join(self, url: URL | str) -> URL:
355
+ """
356
+ Return an absolute URL, using this URL as the base.
357
+
358
+ Eg.
359
+
360
+ url = httpx.URL("https://www.example.com/test")
361
+ url = url.join("/new/path")
362
+ assert url == "https://www.example.com/new/path"
363
+ """
364
+ from urllib.parse import urljoin
365
+
366
+ return URL(urljoin(str(self), str(URL(url))))
367
+
368
+ def __hash__(self) -> int:
369
+ return hash(str(self))
370
+
371
+ def __eq__(self, other: typing.Any) -> bool:
372
+ return isinstance(other, (URL, str)) and str(self) == str(URL(other))
373
+
374
+ def __str__(self) -> str:
375
+ return str(self._uri_reference)
376
+
377
+ def __repr__(self) -> str:
378
+ scheme, userinfo, host, port, path, query, fragment = self._uri_reference
379
+
380
+ if ":" in userinfo:
381
+ # Mask any password component.
382
+ userinfo = f'{userinfo.split(":")[0]}:[secure]'
383
+
384
+ authority = "".join(
385
+ [
386
+ f"{userinfo}@" if userinfo else "",
387
+ f"[{host}]" if ":" in host else host,
388
+ f":{port}" if port is not None else "",
389
+ ]
390
+ )
391
+ url = "".join(
392
+ [
393
+ f"{self.scheme}:" if scheme else "",
394
+ f"//{authority}" if authority else "",
395
+ path,
396
+ f"?{query}" if query is not None else "",
397
+ f"#{fragment}" if fragment is not None else "",
398
+ ]
399
+ )
400
+
401
+ return f"{self.__class__.__name__}({url!r})"
402
+
403
+ @property
404
+ def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover
405
+ import collections
406
+ import warnings
407
+
408
+ warnings.warn("URL.raw is deprecated.")
409
+ RawURL = collections.namedtuple(
410
+ "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"]
411
+ )
412
+ return RawURL(
413
+ raw_scheme=self.raw_scheme,
414
+ raw_host=self.raw_host,
415
+ port=self.port,
416
+ raw_path=self.raw_path,
417
+ )
418
+
419
+
420
+ class QueryParams(typing.Mapping[str, str]):
421
+ """
422
+ URL query parameters, as a multi-dict.
423
+ """
424
+
425
+ def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:
426
+ assert len(args) < 2, "Too many arguments."
427
+ assert not (args and kwargs), "Cannot mix named and unnamed arguments."
428
+
429
+ value = args[0] if args else kwargs
430
+
431
+ if value is None or isinstance(value, (str, bytes)):
432
+ value = value.decode("ascii") if isinstance(value, bytes) else value
433
+ self._dict = parse_qs(value, keep_blank_values=True)
434
+ elif isinstance(value, QueryParams):
435
+ self._dict = {k: list(v) for k, v in value._dict.items()}
436
+ else:
437
+ dict_value: dict[typing.Any, list[typing.Any]] = {}
438
+ if isinstance(value, (list, tuple)):
439
+ # Convert list inputs like:
440
+ # [("a", "123"), ("a", "456"), ("b", "789")]
441
+ # To a dict representation, like:
442
+ # {"a": ["123", "456"], "b": ["789"]}
443
+ for item in value:
444
+ dict_value.setdefault(item[0], []).append(item[1])
445
+ else:
446
+ # Convert dict inputs like:
447
+ # {"a": "123", "b": ["456", "789"]}
448
+ # To dict inputs where values are always lists, like:
449
+ # {"a": ["123"], "b": ["456", "789"]}
450
+ dict_value = {
451
+ k: list(v) if isinstance(v, (list, tuple)) else [v]
452
+ for k, v in value.items()
453
+ }
454
+
455
+ # Ensure that keys and values are neatly coerced to strings.
456
+ # We coerce values `True` and `False` to JSON-like "true" and "false"
457
+ # representations, and coerce `None` values to the empty string.
458
+ self._dict = {
459
+ str(k): [primitive_value_to_str(item) for item in v]
460
+ for k, v in dict_value.items()
461
+ }
462
+
463
+ def keys(self) -> typing.KeysView[str]:
464
+ """
465
+ Return all the keys in the query params.
466
+
467
+ Usage:
468
+
469
+ q = httpx.QueryParams("a=123&a=456&b=789")
470
+ assert list(q.keys()) == ["a", "b"]
471
+ """
472
+ return self._dict.keys()
473
+
474
+ def values(self) -> typing.ValuesView[str]:
475
+ """
476
+ Return all the values in the query params. If a key occurs more than once
477
+ only the first item for that key is returned.
478
+
479
+ Usage:
480
+
481
+ q = httpx.QueryParams("a=123&a=456&b=789")
482
+ assert list(q.values()) == ["123", "789"]
483
+ """
484
+ return {k: v[0] for k, v in self._dict.items()}.values()
485
+
486
+ def items(self) -> typing.ItemsView[str, str]:
487
+ """
488
+ Return all items in the query params. If a key occurs more than once
489
+ only the first item for that key is returned.
490
+
491
+ Usage:
492
+
493
+ q = httpx.QueryParams("a=123&a=456&b=789")
494
+ assert list(q.items()) == [("a", "123"), ("b", "789")]
495
+ """
496
+ return {k: v[0] for k, v in self._dict.items()}.items()
497
+
498
+ def multi_items(self) -> list[tuple[str, str]]:
499
+ """
500
+ Return all items in the query params. Allow duplicate keys to occur.
501
+
502
+ Usage:
503
+
504
+ q = httpx.QueryParams("a=123&a=456&b=789")
505
+ assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]
506
+ """
507
+ multi_items: list[tuple[str, str]] = []
508
+ for k, v in self._dict.items():
509
+ multi_items.extend([(k, i) for i in v])
510
+ return multi_items
511
+
512
+ def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
513
+ """
514
+ Get a value from the query param for a given key. If the key occurs
515
+ more than once, then only the first value is returned.
516
+
517
+ Usage:
518
+
519
+ q = httpx.QueryParams("a=123&a=456&b=789")
520
+ assert q.get("a") == "123"
521
+ """
522
+ if key in self._dict:
523
+ return self._dict[str(key)][0]
524
+ return default
525
+
526
+ def get_list(self, key: str) -> list[str]:
527
+ """
528
+ Get all values from the query param for a given key.
529
+
530
+ Usage:
531
+
532
+ q = httpx.QueryParams("a=123&a=456&b=789")
533
+ assert q.get_list("a") == ["123", "456"]
534
+ """
535
+ return list(self._dict.get(str(key), []))
536
+
537
+ def set(self, key: str, value: typing.Any = None) -> QueryParams:
538
+ """
539
+ Return a new QueryParams instance, setting the value of a key.
540
+
541
+ Usage:
542
+
543
+ q = httpx.QueryParams("a=123")
544
+ q = q.set("a", "456")
545
+ assert q == httpx.QueryParams("a=456")
546
+ """
547
+ q = QueryParams()
548
+ q._dict = dict(self._dict)
549
+ q._dict[str(key)] = [primitive_value_to_str(value)]
550
+ return q
551
+
552
+ def add(self, key: str, value: typing.Any = None) -> QueryParams:
553
+ """
554
+ Return a new QueryParams instance, setting or appending the value of a key.
555
+
556
+ Usage:
557
+
558
+ q = httpx.QueryParams("a=123")
559
+ q = q.add("a", "456")
560
+ assert q == httpx.QueryParams("a=123&a=456")
561
+ """
562
+ q = QueryParams()
563
+ q._dict = dict(self._dict)
564
+ q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]
565
+ return q
566
+
567
+ def remove(self, key: str) -> QueryParams:
568
+ """
569
+ Return a new QueryParams instance, removing the value of a key.
570
+
571
+ Usage:
572
+
573
+ q = httpx.QueryParams("a=123")
574
+ q = q.remove("a")
575
+ assert q == httpx.QueryParams("")
576
+ """
577
+ q = QueryParams()
578
+ q._dict = dict(self._dict)
579
+ q._dict.pop(str(key), None)
580
+ return q
581
+
582
+ def merge(self, params: QueryParamTypes | None = None) -> QueryParams:
583
+ """
584
+ Return a new QueryParams instance, updated with.
585
+
586
+ Usage:
587
+
588
+ q = httpx.QueryParams("a=123")
589
+ q = q.merge({"b": "456"})
590
+ assert q == httpx.QueryParams("a=123&b=456")
591
+
592
+ q = httpx.QueryParams("a=123")
593
+ q = q.merge({"a": "456", "b": "789"})
594
+ assert q == httpx.QueryParams("a=456&b=789")
595
+ """
596
+ q = QueryParams(params)
597
+ q._dict = {**self._dict, **q._dict}
598
+ return q
599
+
600
+ def __getitem__(self, key: typing.Any) -> str:
601
+ return self._dict[key][0]
602
+
603
+ def __contains__(self, key: typing.Any) -> bool:
604
+ return key in self._dict
605
+
606
+ def __iter__(self) -> typing.Iterator[typing.Any]:
607
+ return iter(self.keys())
608
+
609
+ def __len__(self) -> int:
610
+ return len(self._dict)
611
+
612
+ def __bool__(self) -> bool:
613
+ return bool(self._dict)
614
+
615
+ def __hash__(self) -> int:
616
+ return hash(str(self))
617
+
618
+ def __eq__(self, other: typing.Any) -> bool:
619
+ if not isinstance(other, self.__class__):
620
+ return False
621
+ return sorted(self.multi_items()) == sorted(other.multi_items())
622
+
623
+ def __str__(self) -> str:
624
+ return urlencode(self.multi_items())
625
+
626
+ def __repr__(self) -> str:
627
+ class_name = self.__class__.__name__
628
+ query_string = str(self)
629
+ return f"{class_name}({query_string!r})"
630
+
631
+ def update(self, params: QueryParamTypes | None = None) -> None:
632
+ raise RuntimeError(
633
+ "QueryParams are immutable since 0.18.0. "
634
+ "Use `q = q.merge(...)` to create an updated copy."
635
+ )
636
+
637
+ def __setitem__(self, key: str, value: str) -> None:
638
+ raise RuntimeError(
639
+ "QueryParams are immutable since 0.18.0. "
640
+ "Use `q = q.set(key, value)` to create an updated copy."
641
+ )
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/_utils.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ipaddress
4
+ import os
5
+ import re
6
+ import typing
7
+ from urllib.request import getproxies
8
+
9
+ from ._types import PrimitiveData
10
+
11
+ if typing.TYPE_CHECKING: # pragma: no cover
12
+ from ._urls import URL
13
+
14
+
15
+ def primitive_value_to_str(value: PrimitiveData) -> str:
16
+ """
17
+ Coerce a primitive data type into a string value.
18
+
19
+ Note that we prefer JSON-style 'true'/'false' for boolean values here.
20
+ """
21
+ if value is True:
22
+ return "true"
23
+ elif value is False:
24
+ return "false"
25
+ elif value is None:
26
+ return ""
27
+ return str(value)
28
+
29
+
30
+ def get_environment_proxies() -> dict[str, str | None]:
31
+ """Gets proxy information from the environment"""
32
+
33
+ # urllib.request.getproxies() falls back on System
34
+ # Registry and Config for proxies on Windows and macOS.
35
+ # We don't want to propagate non-HTTP proxies into
36
+ # our configuration such as 'TRAVIS_APT_PROXY'.
37
+ proxy_info = getproxies()
38
+ mounts: dict[str, str | None] = {}
39
+
40
+ for scheme in ("http", "https", "all"):
41
+ if proxy_info.get(scheme):
42
+ hostname = proxy_info[scheme]
43
+ mounts[f"{scheme}://"] = (
44
+ hostname if "://" in hostname else f"http://{hostname}"
45
+ )
46
+
47
+ no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]
48
+ for hostname in no_proxy_hosts:
49
+ # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details
50
+ # on how names in `NO_PROXY` are handled.
51
+ if hostname == "*":
52
+ # If NO_PROXY=* is used or if "*" occurs as any one of the comma
53
+ # separated hostnames, then we should just bypass any information
54
+ # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore
55
+ # proxies.
56
+ return {}
57
+ elif hostname:
58
+ # NO_PROXY=.google.com is marked as "all://*.google.com,
59
+ # which disables "www.google.com" but not "google.com"
60
+ # NO_PROXY=google.com is marked as "all://*google.com,
61
+ # which disables "www.google.com" and "google.com".
62
+ # (But not "wwwgoogle.com")
63
+ # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost"
64
+ # NO_PROXY=example.com,::1,localhost,192.168.0.0/16
65
+ if "://" in hostname:
66
+ mounts[hostname] = None
67
+ elif is_ipv4_hostname(hostname):
68
+ mounts[f"all://{hostname}"] = None
69
+ elif is_ipv6_hostname(hostname):
70
+ mounts[f"all://[{hostname}]"] = None
71
+ elif hostname.lower() == "localhost":
72
+ mounts[f"all://{hostname}"] = None
73
+ else:
74
+ mounts[f"all://*{hostname}"] = None
75
+
76
+ return mounts
77
+
78
+
79
+ def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes:
80
+ return value.encode(encoding) if isinstance(value, str) else value
81
+
82
+
83
+ def to_str(value: str | bytes, encoding: str = "utf-8") -> str:
84
+ return value if isinstance(value, str) else value.decode(encoding)
85
+
86
+
87
+ def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:
88
+ return value if isinstance(match_type_of, str) else value.encode()
89
+
90
+
91
+ def unquote(value: str) -> str:
92
+ return value[1:-1] if value[0] == value[-1] == '"' else value
93
+
94
+
95
+ def peek_filelike_length(stream: typing.Any) -> int | None:
96
+ """
97
+ Given a file-like stream object, return its length in number of bytes
98
+ without reading it into memory.
99
+ """
100
+ try:
101
+ # Is it an actual file?
102
+ fd = stream.fileno()
103
+ # Yup, seems to be an actual file.
104
+ length = os.fstat(fd).st_size
105
+ except (AttributeError, OSError):
106
+ # No... Maybe it's something that supports random access, like `io.BytesIO`?
107
+ try:
108
+ # Assuming so, go to end of stream to figure out its length,
109
+ # then put it back in place.
110
+ offset = stream.tell()
111
+ length = stream.seek(0, os.SEEK_END)
112
+ stream.seek(offset)
113
+ except (AttributeError, OSError):
114
+ # Not even that? Sorry, we're doomed...
115
+ return None
116
+
117
+ return length
118
+
119
+
120
+ class URLPattern:
121
+ """
122
+ A utility class currently used for making lookups against proxy keys...
123
+
124
+ # Wildcard matching...
125
+ >>> pattern = URLPattern("all://")
126
+ >>> pattern.matches(httpx.URL("http://example.com"))
127
+ True
128
+
129
+ # Witch scheme matching...
130
+ >>> pattern = URLPattern("https://")
131
+ >>> pattern.matches(httpx.URL("https://example.com"))
132
+ True
133
+ >>> pattern.matches(httpx.URL("http://example.com"))
134
+ False
135
+
136
+ # With domain matching...
137
+ >>> pattern = URLPattern("https://example.com")
138
+ >>> pattern.matches(httpx.URL("https://example.com"))
139
+ True
140
+ >>> pattern.matches(httpx.URL("http://example.com"))
141
+ False
142
+ >>> pattern.matches(httpx.URL("https://other.com"))
143
+ False
144
+
145
+ # Wildcard scheme, with domain matching...
146
+ >>> pattern = URLPattern("all://example.com")
147
+ >>> pattern.matches(httpx.URL("https://example.com"))
148
+ True
149
+ >>> pattern.matches(httpx.URL("http://example.com"))
150
+ True
151
+ >>> pattern.matches(httpx.URL("https://other.com"))
152
+ False
153
+
154
+ # With port matching...
155
+ >>> pattern = URLPattern("https://example.com:1234")
156
+ >>> pattern.matches(httpx.URL("https://example.com:1234"))
157
+ True
158
+ >>> pattern.matches(httpx.URL("https://example.com"))
159
+ False
160
+ """
161
+
162
+ def __init__(self, pattern: str) -> None:
163
+ from ._urls import URL
164
+
165
+ if pattern and ":" not in pattern:
166
+ raise ValueError(
167
+ f"Proxy keys should use proper URL forms rather "
168
+ f"than plain scheme strings. "
169
+ f'Instead of "{pattern}", use "{pattern}://"'
170
+ )
171
+
172
+ url = URL(pattern)
173
+ self.pattern = pattern
174
+ self.scheme = "" if url.scheme == "all" else url.scheme
175
+ self.host = "" if url.host == "*" else url.host
176
+ self.port = url.port
177
+ if not url.host or url.host == "*":
178
+ self.host_regex: typing.Pattern[str] | None = None
179
+ elif url.host.startswith("*."):
180
+ # *.example.com should match "www.example.com", but not "example.com"
181
+ domain = re.escape(url.host[2:])
182
+ self.host_regex = re.compile(f"^.+\\.{domain}$")
183
+ elif url.host.startswith("*"):
184
+ # *example.com should match "www.example.com" and "example.com"
185
+ domain = re.escape(url.host[1:])
186
+ self.host_regex = re.compile(f"^(.+\\.)?{domain}$")
187
+ else:
188
+ # example.com should match "example.com" but not "www.example.com"
189
+ domain = re.escape(url.host)
190
+ self.host_regex = re.compile(f"^{domain}$")
191
+
192
+ def matches(self, other: URL) -> bool:
193
+ if self.scheme and self.scheme != other.scheme:
194
+ return False
195
+ if (
196
+ self.host
197
+ and self.host_regex is not None
198
+ and not self.host_regex.match(other.host)
199
+ ):
200
+ return False
201
+ if self.port is not None and self.port != other.port:
202
+ return False
203
+ return True
204
+
205
+ @property
206
+ def priority(self) -> tuple[int, int, int]:
207
+ """
208
+ The priority allows URLPattern instances to be sortable, so that
209
+ we can match from most specific to least specific.
210
+ """
211
+ # URLs with a port should take priority over URLs without a port.
212
+ port_priority = 0 if self.port is not None else 1
213
+ # Longer hostnames should match first.
214
+ host_priority = -len(self.host)
215
+ # Longer schemes should match first.
216
+ scheme_priority = -len(self.scheme)
217
+ return (port_priority, host_priority, scheme_priority)
218
+
219
+ def __hash__(self) -> int:
220
+ return hash(self.pattern)
221
+
222
+ def __lt__(self, other: URLPattern) -> bool:
223
+ return self.priority < other.priority
224
+
225
+ def __eq__(self, other: typing.Any) -> bool:
226
+ return isinstance(other, URLPattern) and self.pattern == other.pattern
227
+
228
+
229
+ def is_ipv4_hostname(hostname: str) -> bool:
230
+ try:
231
+ ipaddress.IPv4Address(hostname.split("/")[0])
232
+ except Exception:
233
+ return False
234
+ return True
235
+
236
+
237
+ def is_ipv6_hostname(hostname: str) -> bool:
238
+ try:
239
+ ipaddress.IPv6Address(hostname.split("/")[0])
240
+ except Exception:
241
+ return False
242
+ return True
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/httpx/py.typed ADDED
File without changes
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (1.87 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/_compatibility.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/__pycache__/debug.cpython-310.pyc ADDED
Binary file (3.82 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/completion_cache.cpython-310.pyc ADDED
Binary file (1.26 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/environment.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/helpers.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/keywords.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/project.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/api/__pycache__/strings.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/inference/finder.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Searching for names with given scope and name. This is very central in Jedi and
3
+ Python. The name resolution is quite complicated with descripter,
4
+ ``__getattribute__``, ``__getattr__``, ``global``, etc.
5
+
6
+ If you want to understand name resolution, please read the first few chapters
7
+ in http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/.
8
+
9
+ Flow checks
10
+ +++++++++++
11
+
12
+ Flow checks are not really mature. There's only a check for ``isinstance``. It
13
+ would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``.
14
+ Unfortunately every other thing is being ignored (e.g. a == '' would be easy to
15
+ check for -> a is a string). There's big potential in these checks.
16
+ """
17
+
18
+ from parso.tree import search_ancestor
19
+ from parso.python.tree import Name
20
+
21
+ from jedi import settings
22
+ from jedi.inference.arguments import TreeArguments
23
+ from jedi.inference.value import iterable
24
+ from jedi.inference.base_value import NO_VALUES
25
+ from jedi.parser_utils import is_scope
26
+
27
+
28
+ def filter_name(filters, name_or_str):
29
+ """
30
+ Searches names that are defined in a scope (the different
31
+ ``filters``), until a name fits.
32
+ """
33
+ string_name = name_or_str.value if isinstance(name_or_str, Name) else name_or_str
34
+ names = []
35
+ for filter in filters:
36
+ names = filter.get(string_name)
37
+ if names:
38
+ break
39
+
40
+ return list(_remove_del_stmt(names))
41
+
42
+
43
+ def _remove_del_stmt(names):
44
+ # Catch del statements and remove them from results.
45
+ for name in names:
46
+ if name.tree_name is not None:
47
+ definition = name.tree_name.get_definition()
48
+ if definition is not None and definition.type == 'del_stmt':
49
+ continue
50
+ yield name
51
+
52
+
53
+ def check_flow_information(value, flow, search_name, pos):
54
+ """ Try to find out the type of a variable just with the information that
55
+ is given by the flows: e.g. It is also responsible for assert checks.::
56
+
57
+ if isinstance(k, str):
58
+ k. # <- completion here
59
+
60
+ ensures that `k` is a string.
61
+ """
62
+ if not settings.dynamic_flow_information:
63
+ return None
64
+
65
+ result = None
66
+ if is_scope(flow):
67
+ # Check for asserts.
68
+ module_node = flow.get_root_node()
69
+ try:
70
+ names = module_node.get_used_names()[search_name.value]
71
+ except KeyError:
72
+ return None
73
+ names = reversed([
74
+ n for n in names
75
+ if flow.start_pos <= n.start_pos < (pos or flow.end_pos)
76
+ ])
77
+
78
+ for name in names:
79
+ ass = search_ancestor(name, 'assert_stmt')
80
+ if ass is not None:
81
+ result = _check_isinstance_type(value, ass.assertion, search_name)
82
+ if result is not None:
83
+ return result
84
+
85
+ if flow.type in ('if_stmt', 'while_stmt'):
86
+ potential_ifs = [c for c in flow.children[1::4] if c != ':']
87
+ for if_test in reversed(potential_ifs):
88
+ if search_name.start_pos > if_test.end_pos:
89
+ return _check_isinstance_type(value, if_test, search_name)
90
+ return result
91
+
92
+
93
+ def _get_isinstance_trailer_arglist(node):
94
+ if node.type in ('power', 'atom_expr') and len(node.children) == 2:
95
+ # This might be removed if we analyze and, etc
96
+ first, trailer = node.children
97
+ if first.type == 'name' and first.value == 'isinstance' \
98
+ and trailer.type == 'trailer' and trailer.children[0] == '(':
99
+ return trailer
100
+ return None
101
+
102
+
103
+ def _check_isinstance_type(value, node, search_name):
104
+ lazy_cls = None
105
+ trailer = _get_isinstance_trailer_arglist(node)
106
+ if trailer is not None and len(trailer.children) == 3:
107
+ arglist = trailer.children[1]
108
+ args = TreeArguments(value.inference_state, value, arglist, trailer)
109
+ param_list = list(args.unpack())
110
+ # Disallow keyword arguments
111
+ if len(param_list) == 2 and len(arglist.children) == 3:
112
+ (key1, _), (key2, lazy_value_cls) = param_list
113
+ if key1 is None and key2 is None:
114
+ call = _get_call_string(search_name)
115
+ is_instance_call = _get_call_string(arglist.children[0])
116
+ # Do a simple get_code comparison of the strings . They should
117
+ # just have the same code, and everything will be all right.
118
+ # There are ways that this is not correct, if some stuff is
119
+ # redefined in between. However here we don't care, because
120
+ # it's a heuristic that works pretty well.
121
+ if call == is_instance_call:
122
+ lazy_cls = lazy_value_cls
123
+ if lazy_cls is None:
124
+ return None
125
+
126
+ value_set = NO_VALUES
127
+ for cls_or_tup in lazy_cls.infer():
128
+ if isinstance(cls_or_tup, iterable.Sequence) and cls_or_tup.array_type == 'tuple':
129
+ for lazy_value in cls_or_tup.py__iter__():
130
+ value_set |= lazy_value.infer().execute_with_values()
131
+ else:
132
+ value_set |= cls_or_tup.execute_with_values()
133
+ return value_set
134
+
135
+
136
+ def _get_call_string(node):
137
+ if node.parent.type == 'atom_expr':
138
+ return _get_call_string(node.parent)
139
+
140
+ code = ''
141
+ leaf = node.get_first_leaf()
142
+ end = node.get_last_leaf().end_pos
143
+ while leaf.start_pos < end:
144
+ code += leaf.value
145
+ leaf = leaf.get_next_leaf()
146
+ return code
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/contrib/admin/views/main.pyi ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
3
+
4
+ from django.contrib.admin.filters import ListFilter, SimpleListFilter
5
+ from django.contrib.admin.options import ( # noqa: F401
6
+ ModelAdmin,
7
+ IS_POPUP_VAR as IS_POPUP_VAR,
8
+ TO_FIELD_VAR as TO_FIELD_VAR,
9
+ )
10
+ from django.core.handlers.wsgi import WSGIRequest
11
+ from django.db.models.base import Model
12
+ from django.db.models.expressions import Combinable, CombinedExpression, OrderBy
13
+ from django.db.models.query import QuerySet
14
+
15
+ from django.db.models.options import Options
16
+ from django.forms.formsets import BaseFormSet
17
+
18
+ ALL_VAR: str
19
+ ORDER_VAR: str
20
+ ORDER_TYPE_VAR: str
21
+ PAGE_VAR: str
22
+ SEARCH_VAR: str
23
+ ERROR_FLAG: str
24
+ IGNORED_PARAMS: Any
25
+
26
+ class ChangeList:
27
+ model: Type[Model] = ...
28
+ opts: Options = ...
29
+ lookup_opts: Options = ...
30
+ root_queryset: QuerySet = ...
31
+ list_display: List[str] = ...
32
+ list_display_links: List[str] = ...
33
+ list_filter: Tuple = ...
34
+ date_hierarchy: None = ...
35
+ search_fields: Tuple = ...
36
+ list_select_related: bool = ...
37
+ list_per_page: int = ...
38
+ list_max_show_all: int = ...
39
+ model_admin: ModelAdmin = ...
40
+ preserved_filters: str = ...
41
+ sortable_by: Tuple[str] = ...
42
+ page_num: int = ...
43
+ show_all: bool = ...
44
+ is_popup: bool = ...
45
+ to_field: None = ...
46
+ params: Dict[Any, Any] = ...
47
+ list_editable: Tuple = ...
48
+ query: str = ...
49
+ queryset: Any = ...
50
+ title: Any = ...
51
+ pk_attname: Any = ...
52
+ formset: Optional[BaseFormSet]
53
+ def __init__(
54
+ self,
55
+ request: WSGIRequest,
56
+ model: Type[Model],
57
+ list_display: Union[List[Union[Callable, str]], Tuple[str]],
58
+ list_display_links: Optional[Union[List[Callable], List[str], Tuple[str]]],
59
+ list_filter: Union[List[Type[SimpleListFilter]], List[str], Tuple],
60
+ date_hierarchy: Optional[str],
61
+ search_fields: Union[List[str], Tuple],
62
+ list_select_related: Union[Tuple, bool],
63
+ list_per_page: int,
64
+ list_max_show_all: int,
65
+ list_editable: Union[List[str], Tuple],
66
+ model_admin: ModelAdmin,
67
+ sortable_by: Union[List[Callable], List[str], Tuple],
68
+ ) -> None: ...
69
+ def get_filters_params(self, params: None = ...) -> Dict[str, str]: ...
70
+ def get_filters(self, request: WSGIRequest) -> Tuple[List[ListFilter], bool, Dict[str, Union[bool, str]], bool]: ...
71
+ def get_query_string(
72
+ self, new_params: Optional[Dict[str, None]] = ..., remove: Optional[List[str]] = ...
73
+ ) -> str: ...
74
+ result_count: Any = ...
75
+ show_full_result_count: Any = ...
76
+ show_admin_actions: Any = ...
77
+ full_result_count: Any = ...
78
+ result_list: Any = ...
79
+ can_show_all: Any = ...
80
+ multi_page: Any = ...
81
+ paginator: Any = ...
82
+ def get_results(self, request: WSGIRequest) -> None: ...
83
+ def get_ordering_field(self, field_name: Union[Callable, str]) -> Optional[Union[CombinedExpression, str]]: ...
84
+ def get_ordering(self, request: WSGIRequest, queryset: QuerySet) -> List[Union[OrderBy, Combinable, str]]: ...
85
+ def get_ordering_field_columns(self) -> OrderedDict: ...
86
+ def get_queryset(self, request: WSGIRequest) -> QuerySet: ...
87
+ def apply_select_related(self, qs: QuerySet) -> QuerySet: ...
88
+ def has_related_field_in_list_display(self) -> bool: ...
89
+ def url_for_result(self, result: Model) -> str: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/__init__.pyi ADDED
File without changes
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/base.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Tuple
2
+
3
+ from django.db.backends.base.base import BaseDatabaseWrapper
4
+
5
+ def psycopg2_version() -> Tuple[int, ...]: ...
6
+
7
+ PSYCOPG2_VERSION: Tuple[int, ...] = ...
8
+
9
+ class DatabaseWrapper(BaseDatabaseWrapper):
10
+ operators: Dict[str, str] = ...
11
+ pattern_esc: str = ...
12
+ pattern_ops: Dict[str, str] = ...
13
+
14
+ # PostgreSQL backend-specific attributes.
15
+ _named_cursor_idx: int = ...
16
+ @property
17
+ def pg_version(self) -> str: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/client.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ from django.db.backends.base.client import BaseDatabaseClient
4
+
5
+ class DatabaseClient(BaseDatabaseClient):
6
+ executable_name: str = ...
7
+ @classmethod
8
+ def runshell_db(cls, conn_params: Dict[str, str]) -> None: ...
9
+ def runshell(self) -> None: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/creation.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from django.db.backends.base.creation import BaseDatabaseCreation
2
+
3
+ class DatabaseCreation(BaseDatabaseCreation): ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/postgresql/operations.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from django.db.backends.base.operations import BaseDatabaseOperations
2
+
3
+ class DatabaseOperations(BaseDatabaseOperations): ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/__init__.pyi ADDED
File without changes
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/base.pyi ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlite3 import dbapi2 as Database
2
+ from typing import Any, Callable
3
+
4
+ from django.db.backends.base.base import BaseDatabaseWrapper
5
+
6
+ def decoder(conv_func: Callable) -> Callable: ...
7
+
8
+ class DatabaseWrapper(BaseDatabaseWrapper): ...
9
+
10
+ FORMAT_QMARK_REGEX: Any
11
+
12
+ class SQLiteCursorWrapper(Database.Cursor): ...
13
+
14
+ def check_sqlite_version() -> None: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/creation.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from django.db.backends.base.creation import BaseDatabaseCreation
2
+
3
+ class DatabaseCreation(BaseDatabaseCreation): ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/backends/sqlite3/introspection.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+ from django.db.backends.base.introspection import BaseDatabaseIntrospection
4
+
5
+ field_size_re: Any
6
+
7
+ def get_field_size(name: str) -> Optional[int]: ...
8
+
9
+ class FlexibleFieldLookupDict:
10
+ base_data_types_reverse: Any = ...
11
+ def __getitem__(self, key: str) -> Any: ...
12
+
13
+ class DatabaseIntrospection(BaseDatabaseIntrospection): ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/autodetector.pyi ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
2
+
3
+ from django.db.migrations.graph import MigrationGraph
4
+ from django.db.migrations.migration import Migration
5
+ from django.db.migrations.operations.base import Operation
6
+ from django.db.migrations.questioner import MigrationQuestioner
7
+ from django.db.migrations.state import ProjectState
8
+ from django.db.models.fields import Field
9
+
10
+ class MigrationAutodetector:
11
+ from_state: ProjectState = ...
12
+ to_state: ProjectState = ...
13
+ questioner: MigrationQuestioner = ...
14
+ existing_apps: Set[Any] = ...
15
+ def __init__(
16
+ self, from_state: ProjectState, to_state: ProjectState, questioner: Optional[MigrationQuestioner] = ...
17
+ ) -> None: ...
18
+ def changes(
19
+ self,
20
+ graph: MigrationGraph,
21
+ trim_to_apps: Optional[Set[str]] = ...,
22
+ convert_apps: Optional[Set[str]] = ...,
23
+ migration_name: Optional[str] = ...,
24
+ ) -> Dict[str, List[Migration]]: ...
25
+ def deep_deconstruct(self, obj: Any) -> Any: ...
26
+ def only_relation_agnostic_fields(
27
+ self, fields: List[Tuple[str, Field]]
28
+ ) -> List[Tuple[str, List[Any], Dict[str, Union[Callable, int, str]]]]: ...
29
+ def check_dependency(
30
+ self, operation: Operation, dependency: Tuple[str, str, Optional[str], Union[bool, str]]
31
+ ) -> bool: ...
32
+ def add_operation(
33
+ self,
34
+ app_label: str,
35
+ operation: Operation,
36
+ dependencies: Optional[List[Tuple[str, str, Optional[str], Union[bool, str]]]] = ...,
37
+ beginning: bool = ...,
38
+ ) -> None: ...
39
+ def swappable_first_key(self, item: Tuple[str, str]) -> Tuple[str, str]: ...
40
+ renamed_models: Any = ...
41
+ renamed_models_rel: Any = ...
42
+ def generate_renamed_models(self) -> None: ...
43
+ def generate_created_models(self) -> None: ...
44
+ def generate_created_proxies(self) -> None: ...
45
+ def generate_deleted_models(self) -> None: ...
46
+ def generate_deleted_proxies(self) -> None: ...
47
+ renamed_fields: Any = ...
48
+ def generate_renamed_fields(self) -> None: ...
49
+ def generate_added_fields(self) -> None: ...
50
+ def generate_removed_fields(self) -> None: ...
51
+ def generate_altered_fields(self) -> None: ...
52
+ def create_altered_indexes(self) -> None: ...
53
+ def generate_added_indexes(self) -> None: ...
54
+ def generate_removed_indexes(self) -> None: ...
55
+ def generate_altered_unique_together(self) -> None: ...
56
+ def generate_altered_index_together(self) -> None: ...
57
+ def generate_altered_db_table(self) -> None: ...
58
+ def generate_altered_options(self) -> None: ...
59
+ def generate_altered_order_with_respect_to(self) -> None: ...
60
+ def generate_altered_managers(self) -> None: ...
61
+ def arrange_for_graph(
62
+ self, changes: Dict[str, List[Migration]], graph: MigrationGraph, migration_name: Optional[str] = ...
63
+ ) -> Dict[str, List[Migration]]: ...
64
+ @classmethod
65
+ def suggest_name(cls, ops: List[Operation]) -> str: ...
66
+ @classmethod
67
+ def parse_number(cls, name: str) -> int: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/executor.pyi ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, List, Optional, Set, Tuple, Union
2
+
3
+ from django.db import DefaultConnectionProxy
4
+ from django.db.backends.base.base import BaseDatabaseWrapper
5
+ from django.db.migrations.migration import Migration
6
+
7
+ from .loader import MigrationLoader
8
+ from .recorder import MigrationRecorder
9
+ from .state import ProjectState
10
+
11
+ class MigrationExecutor:
12
+ connection: Any = ...
13
+ loader: MigrationLoader = ...
14
+ recorder: MigrationRecorder = ...
15
+ progress_callback: Callable = ...
16
+ def __init__(
17
+ self,
18
+ connection: Optional[Union[DefaultConnectionProxy, BaseDatabaseWrapper]],
19
+ progress_callback: Optional[Callable] = ...,
20
+ ) -> None: ...
21
+ def migration_plan(
22
+ self, targets: Union[List[Tuple[str, Optional[str]]], Set[Tuple[str, str]]], clean_start: bool = ...
23
+ ) -> List[Tuple[Migration, bool]]: ...
24
+ def migrate(
25
+ self,
26
+ targets: Optional[List[Tuple[str, Optional[str]]]],
27
+ plan: Optional[List[Tuple[Migration, bool]]] = ...,
28
+ state: Optional[ProjectState] = ...,
29
+ fake: bool = ...,
30
+ fake_initial: bool = ...,
31
+ ) -> ProjectState: ...
32
+ def collect_sql(self, plan: List[Tuple[Migration, bool]]) -> List[str]: ...
33
+ def apply_migration(
34
+ self, state: ProjectState, migration: Migration, fake: bool = ..., fake_initial: bool = ...
35
+ ) -> ProjectState: ...
36
+ def unapply_migration(self, state: ProjectState, migration: Migration, fake: bool = ...) -> ProjectState: ...
37
+ def check_replacements(self) -> None: ...
38
+ def detect_soft_applied(
39
+ self, project_state: Optional[ProjectState], migration: Migration
40
+ ) -> Tuple[bool, ProjectState]: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/loader.pyi ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Sequence, Set, Tuple, Union
2
+
3
+ from django.db.migrations.migration import Migration
4
+ from django.db.migrations.state import ProjectState
5
+
6
+ MIGRATIONS_MODULE_NAME: str
7
+
8
+ class MigrationLoader:
9
+ connection: Any = ...
10
+ disk_migrations: Dict[Tuple[str, str], Migration] = ...
11
+ applied_migrations: Set[Tuple[str, str]] = ...
12
+ ignore_no_migrations: bool = ...
13
+ def __init__(self, connection: Any, load: bool = ..., ignore_no_migrations: bool = ...) -> None: ...
14
+ @classmethod
15
+ def migrations_module(cls, app_label: str) -> Tuple[Optional[str], bool]: ...
16
+ unmigrated_apps: Set[str] = ...
17
+ migrated_apps: Set[str] = ...
18
+ def load_disk(self) -> None: ...
19
+ def get_migration(self, app_label: str, name_prefix: str) -> Migration: ...
20
+ def get_migration_by_prefix(self, app_label: str, name_prefix: str) -> Migration: ...
21
+ def check_key(self, key: Tuple[str, str], current_app: str) -> Optional[Tuple[str, str]]: ...
22
+ def add_internal_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ...
23
+ def add_external_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ...
24
+ graph: Any = ...
25
+ replacements: Any = ...
26
+ def build_graph(self) -> None: ...
27
+ def check_consistent_history(self, connection: Any) -> None: ...
28
+ def detect_conflicts(self) -> Dict[str, Set[str]]: ...
29
+ def project_state(
30
+ self, nodes: Optional[Union[Tuple[str, str], Sequence[Tuple[str, str]]]] = ..., at_end: bool = ...
31
+ ) -> ProjectState: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/__init__.pyi ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .fields import (
2
+ AddField as AddField,
3
+ AlterField as AlterField,
4
+ RemoveField as RemoveField,
5
+ RenameField as RenameField,
6
+ )
7
+ from .models import (
8
+ AddIndex as AddIndex,
9
+ AlterIndexTogether as AlterIndexTogether,
10
+ AlterModelManagers as AlterModelManagers,
11
+ AlterModelOptions as AlterModelOptions,
12
+ AlterModelTable as AlterModelTable,
13
+ AlterOrderWithRespectTo as AlterOrderWithRespectTo,
14
+ AlterUniqueTogether as AlterUniqueTogether,
15
+ CreateModel as CreateModel,
16
+ DeleteModel as DeleteModel,
17
+ RemoveIndex as RemoveIndex,
18
+ RenameModel as RenameModel,
19
+ AddConstraint as AddConstraint,
20
+ RemoveConstraint as RemoveConstraint,
21
+ )
22
+ from .special import RunPython as RunPython, RunSQL as RunSQL, SeparateDatabaseAndState as SeparateDatabaseAndState
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/base.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List
2
+
3
+ class Operation:
4
+ reversible: bool = ...
5
+ reduces_to_sql: bool = ...
6
+ atomic: bool = ...
7
+ elidable: bool = ...
8
+ serialization_expand_args: Any = ...
9
+ def deconstruct(self): ...
10
+ def state_forwards(self, app_label: Any, state: Any) -> None: ...
11
+ def database_forwards(self, app_label: Any, schema_editor: Any, from_state: Any, to_state: Any) -> None: ...
12
+ def database_backwards(self, app_label: Any, schema_editor: Any, from_state: Any, to_state: Any) -> None: ...
13
+ def describe(self): ...
14
+ def references_model(self, name: str, app_label: str = ...) -> bool: ...
15
+ def references_field(self, model_name: str, name: str, app_label: str = ...) -> bool: ...
16
+ def allow_migrate_model(self, connection_alias: Any, model: Any): ...
17
+ def reduce(self, operation: Operation, in_between: List[Operation], app_label: str = ...) -> bool: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/fields.pyi ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+ from django.db.models.fields import Field
4
+ from .base import Operation
5
+
6
+ class FieldOperation(Operation):
7
+ model_name: str = ...
8
+ model_name_lower: str
9
+ name: str = ...
10
+ def __init__(self, model_name: str, name: str, field: Optional[Field] = ...) -> None: ...
11
+ def name_lower(self) -> str: ...
12
+ def is_same_model_operation(self, operation: FieldOperation) -> bool: ...
13
+ def is_same_field_operation(self, operation: AddField) -> bool: ...
14
+
15
+ class AddField(FieldOperation):
16
+ field: Field = ...
17
+ preserve_default: bool = ...
18
+ def __init__(self, model_name: str, name: str, field: Field, preserve_default: bool = ...) -> None: ...
19
+
20
+ class RemoveField(FieldOperation): ...
21
+
22
+ class AlterField(FieldOperation):
23
+ field: Any = ...
24
+ preserve_default: Any = ...
25
+ def __init__(self, model_name: str, name: str, field: Field, preserve_default: bool = ...) -> None: ...
26
+
27
+ class RenameField(FieldOperation):
28
+ old_name: Any = ...
29
+ new_name: Any = ...
30
+ def __init__(self, model_name: str, old_name: str, new_name: str) -> None: ...
31
+ def old_name_lower(self): ...
32
+ def new_name_lower(self) -> str: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/models.pyi ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Collection, Dict, List, Optional, Sequence, Tuple, Union
2
+
3
+ from django.db.migrations.operations.base import Operation
4
+ from django.db.models.indexes import Index
5
+ from django.db.models.manager import Manager
6
+
7
+ from django.db.models.constraints import BaseConstraint
8
+ from django.db.models.fields import Field
9
+
10
+ class ModelOperation(Operation):
11
+ name: str = ...
12
+ def __init__(self, name: str) -> None: ...
13
+ def name_lower(self) -> str: ...
14
+
15
+ class CreateModel(ModelOperation):
16
+ fields: Sequence[Tuple[str, Field]] = ...
17
+ options: Any = ...
18
+ bases: Optional[Sequence[Union[type, str]]] = ...
19
+ managers: Optional[Sequence[Tuple[str, Manager]]] = ...
20
+ def __init__(
21
+ self,
22
+ name: str,
23
+ fields: Sequence[Tuple[str, Field]],
24
+ options: Optional[Dict[str, Any]] = ...,
25
+ bases: Optional[Sequence[Union[type, str]]] = ...,
26
+ managers: Optional[Sequence[Tuple[str, Manager]]] = ...,
27
+ ) -> None: ...
28
+ def model_to_key(self, model: str) -> List[str]: ...
29
+
30
+ class DeleteModel(ModelOperation): ...
31
+
32
+ class RenameModel(ModelOperation):
33
+ old_name: Any = ...
34
+ new_name: Any = ...
35
+ def __init__(self, old_name: str, new_name: str) -> None: ...
36
+ def old_name_lower(self) -> str: ...
37
+ def new_name_lower(self) -> str: ...
38
+
39
+ class AlterModelTable(ModelOperation):
40
+ table: Optional[str] = ...
41
+ def __init__(self, name: str, table: Optional[str]) -> None: ...
42
+
43
+ class ModelOptionOperation(ModelOperation): ...
44
+ class FieldRelatedOptionOperation(ModelOptionOperation): ...
45
+
46
+ class AlterUniqueTogether(FieldRelatedOptionOperation):
47
+ option_name: str = ...
48
+ unique_together: Collection[Sequence[str]] = ...
49
+ def __init__(self, name: str, unique_together: Optional[Collection[Sequence[str]]]) -> None: ...
50
+
51
+ class AlterIndexTogether(FieldRelatedOptionOperation):
52
+ option_name: str = ...
53
+ index_together: Collection[Sequence[str]] = ...
54
+ def __init__(self, name: str, index_together: Optional[Collection[Sequence[str]]]) -> None: ...
55
+
56
+ class AlterOrderWithRespectTo(FieldRelatedOptionOperation):
57
+ order_with_respect_to: str = ...
58
+ def __init__(self, name: str, order_with_respect_to: str) -> None: ...
59
+
60
+ class AlterModelOptions(ModelOptionOperation):
61
+ ALTER_OPTION_KEYS: Any = ...
62
+ options: Dict[str, str] = ...
63
+ def __init__(self, name: str, options: Dict[str, Any]) -> None: ...
64
+
65
+ class AlterModelManagers(ModelOptionOperation):
66
+ managers: Any = ...
67
+ def __init__(self, name: Any, managers: Any) -> None: ...
68
+
69
+ class IndexOperation(Operation):
70
+ option_name: str = ...
71
+ def model_name_lower(self): ...
72
+
73
+ class AddIndex(IndexOperation):
74
+ model_name: str = ...
75
+ index: Index = ...
76
+ def __init__(self, model_name: str, index: Union[str, Index]) -> None: ...
77
+
78
+ class RemoveIndex(IndexOperation):
79
+ model_name: str = ...
80
+ name: str = ...
81
+ def __init__(self, model_name: str, name: Union[str, Index]) -> None: ...
82
+
83
+ class AddConstraint(IndexOperation):
84
+ def __init__(self, model_name: str, constraint: BaseConstraint): ...
85
+
86
+ class RemoveConstraint(IndexOperation):
87
+ def __init__(self, model_name: str, name: str) -> None: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/special.pyi ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, Optional, Sequence
2
+
3
+ from django.db.backends.base.schema import BaseDatabaseSchemaEditor
4
+ from django.db.migrations.state import StateApps
5
+
6
+ from .base import Operation
7
+
8
+ class SeparateDatabaseAndState(Operation):
9
+ database_operations: Sequence[Operation] = ...
10
+ state_operations: Sequence[Operation] = ...
11
+ def __init__(
12
+ self, database_operations: Sequence[Operation] = ..., state_operations: Sequence[Operation] = ...
13
+ ) -> None: ...
14
+
15
+ class RunSQL(Operation):
16
+ noop: str = ...
17
+ sql: Any = ...
18
+ reverse_sql: Any = ...
19
+ state_operations: Any = ...
20
+ hints: Any = ...
21
+ def __init__(
22
+ self,
23
+ sql: Any,
24
+ reverse_sql: Optional[Any] = ...,
25
+ state_operations: Optional[Any] = ...,
26
+ hints: Optional[Any] = ...,
27
+ elidable: bool = ...,
28
+ ) -> None: ...
29
+
30
+ class RunPython(Operation):
31
+ code: Callable = ...
32
+ reverse_code: Optional[Callable] = ...
33
+ hints: Optional[Dict[str, Any]] = ...
34
+ def __init__(
35
+ self,
36
+ code: Callable,
37
+ reverse_code: Optional[Callable] = ...,
38
+ atomic: Optional[bool] = ...,
39
+ hints: Optional[Dict[str, Any]] = ...,
40
+ elidable: bool = ...,
41
+ ) -> None: ...
42
+ @staticmethod
43
+ def noop(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/operations/utils.pyi ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from django.db.migrations.state import ProjectState
2
+
3
+ from django.db.models.fields import Field
4
+
5
+ def is_referenced_by_foreign_key(state: ProjectState, model_name_lower: str, field: Field, field_name: str) -> bool: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/optimizer.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ from django.db.migrations.operations.base import Operation
4
+
5
+ class MigrationOptimizer:
6
+ def optimize(self, operations: List[Operation], app_label: Optional[str] = ...) -> List[Operation]: ...
7
+ def optimize_inner(self, operations: List[Operation], app_label: Optional[str] = ...) -> List[Operation]: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/state.pyi ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union, Set
2
+
3
+ from django.apps import AppConfig
4
+ from django.apps.registry import Apps
5
+ from django.db.models.base import Model
6
+ from django.db.models.manager import Manager
7
+
8
+ from django.db.models.fields import Field
9
+
10
+ class AppConfigStub(AppConfig): ...
11
+
12
+ class ModelState:
13
+ name: str
14
+ app_label: str
15
+ fields: List[Tuple[str, Field]]
16
+ options: Dict[str, Any] = ...
17
+ bases: Tuple[Type[Model]] = ...
18
+ managers: List[Tuple[str, Manager]] = ...
19
+ def __init__(
20
+ self,
21
+ app_label: str,
22
+ name: str,
23
+ fields: List[Tuple[str, Field]],
24
+ options: Optional[Dict[str, Any]] = ...,
25
+ bases: Optional[Sequence[Union[Type[Model], str]]] = ...,
26
+ managers: Optional[List[Tuple[str, Manager]]] = ...,
27
+ ) -> None: ...
28
+ def clone(self) -> ModelState: ...
29
+ def construct_managers(self) -> Iterator[Tuple[str, Manager]]: ...
30
+ @classmethod
31
+ def from_model(cls, model: Type[Model], exclude_rels: bool = ...) -> ModelState: ...
32
+ def get_field_by_name(self, name: str) -> Field: ...
33
+ @property
34
+ def name_lower(self) -> str: ...
35
+ def render(self, apps: Apps) -> Any: ...
36
+
37
+ def get_related_models_tuples(model: Type[Model]) -> Set[Tuple[str, str]]: ...
38
+ def get_related_models_recursive(model: Type[Model]) -> Set[Tuple[str, str]]: ...
39
+
40
+ class ProjectState:
41
+ is_delayed: bool
42
+ models: Dict[Any, Any]
43
+ real_apps: List[str]
44
+ def __init__(
45
+ self, models: Optional[Dict[Tuple[str, str], ModelState]] = ..., real_apps: Optional[List[str]] = ...
46
+ ) -> None: ...
47
+ def add_model(self, model_state: ModelState) -> None: ...
48
+ @property
49
+ def apps(self) -> StateApps: ...
50
+ def clear_delayed_apps_cache(self) -> None: ...
51
+ def clone(self) -> ProjectState: ...
52
+ @property
53
+ def concrete_apps(self) -> StateApps: ...
54
+ @classmethod
55
+ def from_apps(cls, apps: Apps) -> ProjectState: ...
56
+ def reload_model(self, app_label: str, model_name: str, delay: bool = ...) -> None: ...
57
+ def reload_models(self, models: List[Any], delay: bool = ...) -> None: ...
58
+ def remove_model(self, app_label: str, model_name: str) -> None: ...
59
+
60
+ class StateApps(Apps):
61
+ real_models: List[ModelState]
62
+ def __init__(
63
+ self, real_apps: List[str], models: Dict[Tuple[str, str], ModelState], ignore_swappable: bool = ...
64
+ ) -> None: ...
65
+ def bulk_update(self) -> Iterator[None]: ...
66
+ def clone(self) -> StateApps: ...
67
+ def render_multiple(self, model_states: List[ModelState]) -> None: ...
68
+ def unregister_model(self, app_label: str, model_name: str) -> None: ...
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/forms/__init__.pyi ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.core.exceptions import ValidationError as ValidationError
2
+
3
+ from .forms import Form as Form, BaseForm as BaseForm
4
+
5
+ from .formsets import BaseFormSet as BaseFormSet, all_valid as all_valid, formset_factory as formset_factory
6
+
7
+ from .models import (
8
+ ModelForm as ModelForm,
9
+ ModelChoiceField as ModelChoiceField,
10
+ ModelMultipleChoiceField as ModelMultipleChoiceField,
11
+ model_to_dict as model_to_dict,
12
+ BaseModelForm as BaseModelForm,
13
+ BaseInlineFormSet as BaseInlineFormSet,
14
+ BaseModelFormSet as BaseModelFormSet,
15
+ fields_for_model as fields_for_model,
16
+ inlineformset_factory as inlineformset_factory,
17
+ modelform_factory as modelform_factory,
18
+ InlineForeignKeyField as InlineForeignKeyField,
19
+ ModelChoiceIterator as ModelChoiceIterator,
20
+ ModelFormMetaclass as ModelFormMetaclass,
21
+ ModelFormOptions as ModelFormOptions,
22
+ modelformset_factory as modelformset_factory,
23
+ )
24
+
25
+ from .widgets import (
26
+ Widget as Widget,
27
+ ChoiceWidget as ChoiceWidget,
28
+ NumberInput as NumberInput,
29
+ Select as Select,
30
+ CheckboxInput as CheckboxInput,
31
+ CheckboxSelectMultiple as CheckboxSelectMultiple,
32
+ Media as Media,
33
+ MultiWidget as MultiWidget,
34
+ TextInput as TextInput,
35
+ Textarea as Textarea,
36
+ Input as Input,
37
+ ClearableFileInput as ClearableFileInput,
38
+ DateInput as DateInput,
39
+ DateTimeBaseInput as DateTimeBaseInput,
40
+ DateTimeInput as DateTimeInput,
41
+ EmailInput as EmailInput,
42
+ FileInput as FileInput,
43
+ HiddenInput as HiddenInput,
44
+ MultipleHiddenInput as MultipleHiddenInput,
45
+ NullBooleanSelect as NullBooleanSelect,
46
+ PasswordInput as PasswordInput,
47
+ RadioSelect as RadioSelect,
48
+ SelectMultiple as SelectMultiple,
49
+ TimeInput as TimeInput,
50
+ URLInput as URLInput,
51
+ SelectDateWidget as SelectDateWidget,
52
+ SplitHiddenDateTimeWidget as SplitHiddenDateTimeWidget,
53
+ SplitDateTimeWidget as SplitDateTimeWidget,
54
+ )
55
+
56
+ from .fields import (
57
+ Field as Field,
58
+ CharField as CharField,
59
+ ChoiceField as ChoiceField,
60
+ DurationField as DurationField,
61
+ FileField as FileField,
62
+ ImageField as ImageField,
63
+ DateTimeField as DateTimeField,
64
+ DateField as DateField,
65
+ BooleanField as BooleanField,
66
+ EmailField as EmailField,
67
+ FloatField as FloatField,
68
+ MultiValueField as MultiValueField,
69
+ MultipleChoiceField as MultipleChoiceField,
70
+ NullBooleanField as NullBooleanField,
71
+ SplitDateTimeField as SplitDateTimeField,
72
+ TimeField as TimeField,
73
+ IntegerField as IntegerField,
74
+ FilePathField as FilePathField,
75
+ DecimalField as DecimalField,
76
+ UUIDField as UUIDField,
77
+ URLField as URLField,
78
+ ComboField as ComboField,
79
+ GenericIPAddressField as GenericIPAddressField,
80
+ RegexField as RegexField,
81
+ SlugField as SlugField,
82
+ TypedChoiceField as TypedChoiceField,
83
+ TypedMultipleChoiceField as TypedMultipleChoiceField,
84
+ )
85
+
86
+ from .boundfield import BoundField as BoundField, BoundWidget as BoundWidget
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/forms/boundfield.pyi ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ from django.forms.fields import Field
4
+ from django.forms.forms import BaseForm
5
+ from django.forms.renderers import DjangoTemplates
6
+ from django.forms.utils import ErrorList
7
+ from django.forms.widgets import Widget
8
+ from django.utils.safestring import SafeText
9
+
10
+ class BoundField:
11
+ initial: Any
12
+ form: BaseForm = ...
13
+ field: Field = ...
14
+ name: str = ...
15
+ html_name: str = ...
16
+ html_initial_name: str = ...
17
+ html_initial_id: str = ...
18
+ label: str = ...
19
+ help_text: str = ...
20
+ def __init__(self, form: BaseForm, field: Field, name: str) -> None: ...
21
+ def subwidgets(self) -> List[BoundWidget]: ...
22
+ def __bool__(self) -> bool: ...
23
+ def __iter__(self): ...
24
+ def __len__(self) -> int: ...
25
+ def __getitem__(self, idx: Union[int, slice, str]) -> Union[List[BoundWidget], BoundWidget]: ...
26
+ @property
27
+ def errors(self) -> ErrorList: ...
28
+ def as_widget(self, widget: Optional[Widget] = ..., attrs: None = ..., only_initial: bool = ...) -> SafeText: ...
29
+ def as_text(self, attrs: None = ..., **kwargs: Any) -> SafeText: ...
30
+ def as_textarea(self, attrs: None = ..., **kwargs: Any) -> SafeText: ...
31
+ def as_hidden(self, attrs: None = ..., **kwargs: Any) -> SafeText: ...
32
+ @property
33
+ def data(self) -> Any: ...
34
+ def value(self) -> Any: ...
35
+ def label_tag(
36
+ self, contents: Optional[str] = ..., attrs: Optional[Dict[str, str]] = ..., label_suffix: Optional[str] = ...
37
+ ) -> SafeText: ...
38
+ def css_classes(self, extra_classes: None = ...) -> str: ...
39
+ @property
40
+ def is_hidden(self) -> bool: ...
41
+ @property
42
+ def auto_id(self) -> str: ...
43
+ @property
44
+ def id_for_label(self) -> str: ...
45
+ def build_widget_attrs(
46
+ self, attrs: Dict[str, str], widget: Optional[Widget] = ...
47
+ ) -> Dict[str, Union[bool, str]]: ...
48
+
49
+ class BoundWidget:
50
+ parent_widget: Widget = ...
51
+ data: Dict[str, Any] = ...
52
+ renderer: DjangoTemplates = ...
53
+ def __init__(self, parent_widget: Widget, data: Dict[str, Any], renderer: DjangoTemplates) -> None: ...
54
+ def tag(self, wrap_label: bool = ...) -> SafeText: ...
55
+ @property
56
+ def template_name(self) -> str: ...
57
+ @property
58
+ def id_for_label(self) -> str: ...
59
+ @property
60
+ def choice_label(self) -> str: ...