repositori / bagas / requests

requests public ready

https://github.com/psf/requests commit 3c7baaa 48 berkas · 374 potongan 2026-11-21T15:17:50Z
48berkas
36berkas python
374potongan
python 36 markdown 5 yaml 2 text 2 toml 1 css 1 html 1
src/requests/_types.pypython 208 baris ditampilkan
1
"""
2
requests._types
3
~~~~~~~~~~~~~~~
4
5
This module contains type aliases used internally by the Requests library.
6
These types are not part of the public API and must not be relied upon
7
by external code.
8
"""
9
10
from __future__ import annotations
11
12
from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence
13
from typing import (
14
TYPE_CHECKING,
15
Any,
16
Protocol,
17
TypeAlias,
18
TypeVar,
19
runtime_checkable,
20
)
21
22
_T_co = TypeVar("_T_co", covariant=True)
23
_KT_co = TypeVar("_KT_co", covariant=True)
24
_VT_co = TypeVar("_VT_co", covariant=True)
25
26
27
@runtime_checkable
28
class SupportsRead(Protocol[_T_co]):
29
def read(self, length: int = ..., /) -> _T_co: ...
30
31
32
def has_read(obj: Any) -> TypeIs[SupportsRead[str | bytes]]:
33
"""Check if obj supports read, including __getattr__ based proxies."""
34
return isinstance(obj, SupportsRead) or hasattr(obj, "read")
35
36
37
@runtime_checkable
38
class SupportsItems(Protocol[_KT_co, _VT_co]):
39
def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...
40
41
42
# These are needed at runtime for default_hooks() return type
43
HookType: TypeAlias = Callable[["Response"], Any]
44
HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType]
45
46
47
def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]:
48
"""Verify a PreparedRequest has been fully prepared."""
49
if TYPE_CHECKING:
50
return request.url is not None and request.method is not None
51
# noop at runtime to avoid AssertionError
52
return True
48
"""Verify a PreparedRequest has been fully prepared."""
49
if TYPE_CHECKING:
50
return request.url is not None and request.method is not None
51
# noop at runtime to avoid AssertionError
52
return True
53
54
55
if TYPE_CHECKING:
56
from http.cookiejar import CookieJar
57
from typing import TypeAlias, TypedDict
58
59
from typing_extensions import (
60
Buffer, # TODO: move to collections.abc when Python >= 3.12
61
TypeIs, # TODO: move to typing when Python >= 3.13
62
)
63
64
from .auth import AuthBase
65
from .cookies import RequestsCookieJar
66
from .models import PreparedRequest, Response
67
from .structures import CaseInsensitiveDict
68
69
class _ValidatedRequest(PreparedRequest):
70
"""Subtype asserting a PreparedRequest has been fully prepared before calling.
71
72
The override suppression is required because mutable attribute types are
73
invariant (Liskov), but we only narrow after preparation is complete. This
74
is the explicit contract for Requests but Python's typing doesn't have a
75
better way to represent the requirement.
76
"""
77
78
url: str # type: ignore[reportIncompatibleVariableOverride]
79
method: str # type: ignore[reportIncompatibleVariableOverride]
80
81
# Type aliases for core API concepts (ordered by request() signature)
82
UriType: TypeAlias = str | bytes
83
84
_ParamsMappingKeyType: TypeAlias = str | bytes | int | float
85
_ParamsMappingValueType: TypeAlias = (
86
str | bytes | int | float | Iterable[str | bytes | int | float] | None
87
)
88
ParamsType: TypeAlias = (
89
SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType]
90
| tuple[tuple[_ParamsMappingKeyType, _ParamsMappingValueType], ...]
91
| Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]]
92
| str
93
| bytes
94
| None
95
)
91
| Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]]
92
| str
93
| bytes
94
| None
95
)
96
97
KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | SupportsItems[Any, Any]
98
99
RawDataType: TypeAlias = KVDataType | str | bytes
100
StreamDataType: TypeAlias = SupportsRead[str | bytes]
101
EncodableDataType: TypeAlias = RawDataType | StreamDataType
102
103
DataType: TypeAlias = (
104
KVDataType
105
| Iterable[bytes | str]
106
| str
107
| bytes
108
| Buffer
109
| SupportsRead[str | bytes]
110
| None
111
)
112
113
BodyType: TypeAlias = (
114
bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None
115
)
116
117
HeadersType: TypeAlias = Mapping[str, str | bytes] | None
118
119
CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str]
120
121
# Building blocks for FilesType
122
_FileName: TypeAlias = str | None
123
_FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes
124
_FileSpecBasic: TypeAlias = tuple[_FileName, _FileContent]
125
_FileSpecWithContentType: TypeAlias = tuple[_FileName, _FileContent, str]
126
_FileSpecWithHeaders: TypeAlias = tuple[
127
_FileName, _FileContent, str, CaseInsensitiveDict[str] | Mapping[str, str]
128
]
129
_FileSpec: TypeAlias = (
130
_FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders
131
)
132
FilesType: TypeAlias = (
133
Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None
134
)
130
_FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders
131
)
132
FilesType: TypeAlias = (
133
Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None
134
)
135
136
AuthType: TypeAlias = (
137
tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None
138
)
139
140
TimeoutType: TypeAlias = float | tuple[float | None, float | None] | None
141
ProxiesType: TypeAlias = MutableMapping[str, str]
142
HooksType: TypeAlias = dict[str, list[HookType]] | None
143
VerifyType: TypeAlias = bool | str
144
CertType: TypeAlias = str | tuple[str, str] | None
145
JsonType: TypeAlias = (
146
None
147
| bool
148
| int
149
| float
150
| str
151
| Sequence["JsonType"]
152
| Mapping[str, "JsonType"]
153
)
154
155
# TypedDicts for Unpack kwargs (PEP 692)
156
157
class BaseRequestKwargs(TypedDict, total=False):
158
headers: HeadersType
159
cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
160
files: FilesType
161
auth: AuthType
162
timeout: TimeoutType
163
allow_redirects: bool
164
proxies: dict[str, str] | None
165
hooks: HooksInputType | None
166
stream: bool | None
167
verify: VerifyType | None
168
cert: CertType
169
170
class RequestKwargs(BaseRequestKwargs, total=False):
171
"""kwargs for request(), options(), head(), delete()."""
172
173
params: ParamsType
174
data: DataType
175
json: JsonType
171
"""kwargs for request(), options(), head(), delete()."""
172
173
params: ParamsType
174
data: DataType
175
json: JsonType
176
177
class GetKwargs(BaseRequestKwargs, total=False):
178
data: DataType
179
json: JsonType
180
181
class PostKwargs(BaseRequestKwargs, total=False):
182
params: ParamsType
183
184
class DataKwargs(BaseRequestKwargs, total=False):
185
"""kwargs for put(), patch()."""
186
187
params: ParamsType
188
json: JsonType