clientx 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clientx/__init__.py +39 -0
- clientx/_arguments.py +65 -0
- clientx/_builder.py +429 -0
- clientx/_class_setup.py +252 -0
- clientx/_client.py +300 -0
- clientx/_decoding.py +240 -0
- clientx/_endpoint.py +276 -0
- clientx/_method.py +198 -0
- clientx/_planner.py +1281 -0
- clientx/_registry.py +32 -0
- clientx/_signature.py +312 -0
- clientx/_tools.py +440 -0
- clientx/_types.py +313 -0
- clientx/_version.py +5 -0
- clientx/arguments.py +60 -0
- clientx/exceptions.py +61 -0
- clientx/method.py +16 -0
- clientx/py.typed +0 -0
- clientx/tools.py +23 -0
- clientx-0.1.0.dist-info/METADATA +176 -0
- clientx-0.1.0.dist-info/RECORD +23 -0
- clientx-0.1.0.dist-info/WHEEL +4 -0
- clientx-0.1.0.dist-info/licenses/LICENSE +21 -0
clientx/_planner.py
ADDED
|
@@ -0,0 +1,1281 @@
|
|
|
1
|
+
"""Plan how an endpoint's calls become requests, when its class is defined.
|
|
2
|
+
|
|
3
|
+
``Endpoint.set_up_request`` calls ``plan_request`` with the endpoint's final
|
|
4
|
+
path template (any resource prefix joined on), its parameters, and whether it's
|
|
5
|
+
``async def``. It checks that they fit together, raising ``DefinitionError`` if
|
|
6
|
+
they don't, and returns the ``RequestPlan`` that ``_builder.build_request``
|
|
7
|
+
follows on each call. The planner decides everything, ``Send`` options
|
|
8
|
+
included, and bakes it into the plan, so the builder never reads annotations,
|
|
9
|
+
``Send`` or the specs.
|
|
10
|
+
|
|
11
|
+
Where each parameter goes is decided once, and never guessed:
|
|
12
|
+
|
|
13
|
+
1. A parameter that a path placeholder names fills it. It must be a plain value
|
|
14
|
+
that can't be ``None``, with no helper but ``Url()``, no alias, and no
|
|
15
|
+
``Send``.
|
|
16
|
+
2. Every other parameter has a ``clientx.arguments`` helper in its outermost
|
|
17
|
+
``Annotated``, and goes to that helper's ``build_request`` argument. A
|
|
18
|
+
parameter without one is an error, and so is a helper or ``Send`` anywhere
|
|
19
|
+
else in its type, a default inside a helper, or a helper or ``Send`` on a
|
|
20
|
+
model's field.
|
|
21
|
+
|
|
22
|
+
A pydantic serializer in a parameter's type is an error too: the builder sends
|
|
23
|
+
a value by its own type, so it wouldn't run.
|
|
24
|
+
|
|
25
|
+
What each argument takes is an ``HttpxArgumentSpec`` subclass, one per
|
|
26
|
+
argument, so a rule that differs by argument lives in that argument's class:
|
|
27
|
+
|
|
28
|
+
- A plain value is on an allow-list: ``str``, ``int``, ``float``, ``bool``,
|
|
29
|
+
``Enum``, ``date``, ``datetime``, ``time``, ``UUID``, ``Decimal``, ``bytes``,
|
|
30
|
+
a ``Literal`` of those, or a ``NewType`` of one. ``Any``, or no annotation,
|
|
31
|
+
is the escape hatch.
|
|
32
|
+
- The query string and the form take a plain value, or a collection of them,
|
|
33
|
+
which repeats the key, or either, as ``str | list[str]`` does; headers take
|
|
34
|
+
a plain value. A model, dataclass or mapping marked ``Query()``,
|
|
35
|
+
``Header()`` or ``Form()`` is spread into it, one value per field, computed
|
|
36
|
+
fields included, and each field follows the same rule. A model with its own
|
|
37
|
+
model serializer is spread by what it dumps, like a mapping.
|
|
38
|
+
- A file is ``bytes``, a binary file, or a ``(filename, content[,
|
|
39
|
+
content_type[, headers]])`` tuple, never ``str``. A list of files repeats the
|
|
40
|
+
field, and so can several ``File()`` parameters.
|
|
41
|
+
- The raw body, one ``Body()`` parameter, is ``str``, ``bytes``, or a stream of
|
|
42
|
+
bytes that matches the client, sync or async.
|
|
43
|
+
- A JSON field takes any value. A lone ``Json()`` parameter that isn't a plain
|
|
44
|
+
value, ``Any`` included, is the whole body, unless it has
|
|
45
|
+
``Send(embed=True)``.
|
|
46
|
+
- A request has one kind of body: JSON, raw content, or a form of ``Form()``
|
|
47
|
+
and ``File()`` parameters. A ``Form()`` parameter with
|
|
48
|
+
``Send(json_part=True)`` takes any value, sent as a JSON part of the form.
|
|
49
|
+
- Two values sent to one argument under one key raise, except files; header
|
|
50
|
+
keys compare case-insensitively. A header name must be ASCII. A spread
|
|
51
|
+
mapping's keys exist only at the call, and so do those of a model with its
|
|
52
|
+
own model serializer, so the builder checks those, and a clash with one is
|
|
53
|
+
the caller's to avoid.
|
|
54
|
+
- ``Send(exclude_unset=True)`` leaves out a parameter the caller didn't pass,
|
|
55
|
+
as well as a model's unset fields. The dump options must fit the type, since
|
|
56
|
+
pydantic ignores them silently otherwise: ``exclude_none`` and
|
|
57
|
+
``exclude_defaults`` need a model or pydantic dataclass, and
|
|
58
|
+
``exclude_unset`` a default other than ``None``, or a pydantic model, to act
|
|
59
|
+
on. A ``Form()`` takes ``exclude_none`` only on a JSON part.
|
|
60
|
+
|
|
61
|
+
The path template has ``{name}``, filled with one segment, and ``{name:path}``,
|
|
62
|
+
whose value keeps its slashes. There are no literal braces: any brace that
|
|
63
|
+
isn't part of a placeholder raises.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
from __future__ import annotations
|
|
67
|
+
|
|
68
|
+
import io
|
|
69
|
+
from collections.abc import AsyncIterable, Callable, Collection, Iterable, Mapping, Sequence
|
|
70
|
+
from dataclasses import dataclass, fields, is_dataclass
|
|
71
|
+
from datetime import date, datetime, time
|
|
72
|
+
from decimal import Decimal
|
|
73
|
+
from enum import Enum
|
|
74
|
+
from string import Formatter
|
|
75
|
+
from types import NoneType, UnionType
|
|
76
|
+
from typing import (
|
|
77
|
+
IO,
|
|
78
|
+
Any,
|
|
79
|
+
ClassVar,
|
|
80
|
+
Literal,
|
|
81
|
+
TextIO,
|
|
82
|
+
TypeAliasType,
|
|
83
|
+
Union,
|
|
84
|
+
cast,
|
|
85
|
+
get_args,
|
|
86
|
+
get_origin,
|
|
87
|
+
get_type_hints,
|
|
88
|
+
)
|
|
89
|
+
from uuid import UUID
|
|
90
|
+
|
|
91
|
+
from pydantic import BaseModel, PlainSerializer, WrapSerializer
|
|
92
|
+
from pydantic.dataclasses import is_pydantic_dataclass
|
|
93
|
+
from pydantic_core import PydanticUndefined
|
|
94
|
+
|
|
95
|
+
from clientx._arguments import get_httpx_argument
|
|
96
|
+
from clientx._signature import NO_VALUE, ParameterInfo, unwrap_annotated
|
|
97
|
+
from clientx._types import HttpxArgument, Send
|
|
98
|
+
from clientx.exceptions import DefinitionError
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- The plan -----------------------------------------------------------------
|
|
102
|
+
@dataclass(frozen=True, slots=True)
|
|
103
|
+
class RequestPlan:
|
|
104
|
+
"""How a call's arguments become the request, worked out once per endpoint.
|
|
105
|
+
|
|
106
|
+
The planner makes it when the class is defined; the builder follows it on
|
|
107
|
+
each call.
|
|
108
|
+
|
|
109
|
+
Attributes:
|
|
110
|
+
path: The path template, split into text and placeholders, for the
|
|
111
|
+
builder to fill in.
|
|
112
|
+
parameters: The parameters sent under a key, and the ones spread
|
|
113
|
+
into an argument, in signature order.
|
|
114
|
+
body: The parameter that's the whole body, or ``None``: one
|
|
115
|
+
``Body()`` parameter, or a lone ``Json()`` one. Its ``key`` isn't
|
|
116
|
+
used, and a ``None`` value means no body.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
path: tuple[str | PathPlaceholder, ...]
|
|
120
|
+
parameters: tuple[PlannedParameter | SpreadParameter, ...] = ()
|
|
121
|
+
body: PlannedParameter | None = None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, slots=True)
|
|
125
|
+
class DumpOptions:
|
|
126
|
+
"""Pydantic's dump options for a parameter's value, from its ``Send``.
|
|
127
|
+
|
|
128
|
+
The planner sets them; the builder passes them to pydantic as they are,
|
|
129
|
+
without reading ``Send``.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
exclude_unset: bool = False
|
|
133
|
+
exclude_none: bool = False
|
|
134
|
+
exclude_defaults: bool = False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True, slots=True)
|
|
138
|
+
class PlannedParameter:
|
|
139
|
+
"""Where a parameter's value goes, and the key it's sent under.
|
|
140
|
+
|
|
141
|
+
Attributes:
|
|
142
|
+
name: The parameter's name, and its key in the call's arguments.
|
|
143
|
+
httpx_argument: The ``build_request`` argument it goes to.
|
|
144
|
+
key: The name it's sent under, such as the query parameter's.
|
|
145
|
+
many: The value can be a collection, which repeats the key. Whether
|
|
146
|
+
it is one is decided at the call, so ``str | list[str]`` takes
|
|
147
|
+
either, and a ``str`` is always one value, not one per character.
|
|
148
|
+
sends_null: A ``None`` passed explicitly is sent as ``null``. The
|
|
149
|
+
planner sets it from the spec, so the builder needn't read one.
|
|
150
|
+
only_if_passed: Left out when the caller didn't pass it, from
|
|
151
|
+
``Send(exclude_unset=True)``, so the server's default applies.
|
|
152
|
+
json_part: A form field sent as its own part of a multipart form, as
|
|
153
|
+
JSON, from ``Send(json_part=True)``.
|
|
154
|
+
dump: How pydantic dumps the value, for a model inside it.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
name: str
|
|
158
|
+
httpx_argument: HttpxArgument
|
|
159
|
+
key: str
|
|
160
|
+
many: bool = False
|
|
161
|
+
sends_null: bool = False
|
|
162
|
+
only_if_passed: bool = False
|
|
163
|
+
json_part: bool = False
|
|
164
|
+
dump: DumpOptions = DumpOptions()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass(frozen=True, slots=True)
|
|
168
|
+
class SpreadParameter:
|
|
169
|
+
"""A model, dataclass or mapping parameter spread into a text argument.
|
|
170
|
+
|
|
171
|
+
Attributes:
|
|
172
|
+
name: The parameter's name, and its key in the call's arguments.
|
|
173
|
+
httpx_argument: The ``build_request`` argument its fields go to.
|
|
174
|
+
keys: Each field's attribute name, and the key it's sent under.
|
|
175
|
+
``None`` for a mapping, or a model with its own model serializer:
|
|
176
|
+
what it dumps is sent, each key as it is, known only at the call.
|
|
177
|
+
many: A list in a field repeats the key, since the argument takes
|
|
178
|
+
lists. Without it, a list is sent as one text value.
|
|
179
|
+
only_if_passed: Left out when the caller didn't pass it, from
|
|
180
|
+
``Send(exclude_unset=True)``.
|
|
181
|
+
dump: How pydantic dumps the value before its fields are sent.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
name: str
|
|
185
|
+
httpx_argument: HttpxArgument
|
|
186
|
+
keys: tuple[tuple[str, str], ...] | None = None
|
|
187
|
+
many: bool = False
|
|
188
|
+
only_if_passed: bool = False
|
|
189
|
+
dump: DumpOptions = DumpOptions()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# --- Entry point --------------------------------------------------------------
|
|
193
|
+
def plan_request(path_template: str, parameters: Sequence[ParameterInfo], *, is_async: bool) -> RequestPlan:
|
|
194
|
+
"""Work out an endpoint's ``RequestPlan`` from its path and parameters.
|
|
195
|
+
|
|
196
|
+
``is_async`` says whether the endpoint is ``async def``, which is also
|
|
197
|
+
whether its client is async, since each kind of endpoint goes on its own
|
|
198
|
+
kind of client. A streamed body must match it.
|
|
199
|
+
"""
|
|
200
|
+
path = _parse_path(path_template)
|
|
201
|
+
path_placeholders = {part.name: part for part in path if isinstance(part, PathPlaceholder)}
|
|
202
|
+
|
|
203
|
+
parameter_names = {parameter.name for parameter in parameters}
|
|
204
|
+
for placeholder in path_placeholders.values():
|
|
205
|
+
if placeholder.name not in parameter_names:
|
|
206
|
+
raise DefinitionError(
|
|
207
|
+
f"Path {path_template!r} has the placeholder {placeholder}, "
|
|
208
|
+
f"but no parameter is named {placeholder.name!r}. "
|
|
209
|
+
"Add the parameter, or remove the placeholder."
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
lone_body = _find_lone_body(parameters)
|
|
213
|
+
body: PlannedParameter | None = None
|
|
214
|
+
planned: list[PlannedParameter | SpreadParameter] = []
|
|
215
|
+
for parameter in parameters:
|
|
216
|
+
# First, so a nested helper gets its own message rather than "needs a
|
|
217
|
+
# helper": ParameterInfo only reads the outermost Annotated.
|
|
218
|
+
_check_nested(parameter)
|
|
219
|
+
_check_helper_default(parameter)
|
|
220
|
+
_check_model_fields(parameter)
|
|
221
|
+
_check_serializers(parameter)
|
|
222
|
+
placeholder = path_placeholders.get(parameter.name)
|
|
223
|
+
if placeholder is not None:
|
|
224
|
+
_check_path_parameter(parameter, placeholder, path_template)
|
|
225
|
+
continue
|
|
226
|
+
argument = _helper_argument(parameter, path_template)
|
|
227
|
+
if parameter is lone_body or _SPECS[argument].whole_body:
|
|
228
|
+
body = _plan_body(parameter, argument, is_async=is_async)
|
|
229
|
+
else:
|
|
230
|
+
planned.append(_plan_keyed(parameter, argument))
|
|
231
|
+
|
|
232
|
+
# Then the parameters together.
|
|
233
|
+
_check_one_body(parameters)
|
|
234
|
+
_check_one_whole_body(parameters)
|
|
235
|
+
_check_keys(planned)
|
|
236
|
+
return RequestPlan(path=path, parameters=tuple(planned), body=body)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# --- Specs: what each build_request argument takes ----------------------------
|
|
240
|
+
class HttpxArgumentSpec:
|
|
241
|
+
"""What one ``build_request`` argument takes. Subclass it per argument.
|
|
242
|
+
|
|
243
|
+
The planner asks the spec rather than testing for particular arguments, so
|
|
244
|
+
a rule that differs by argument is changed in that argument's class. Each
|
|
245
|
+
subclass lists only what differs from the defaults here. The classes are
|
|
246
|
+
used as they are, never instantiated.
|
|
247
|
+
|
|
248
|
+
Attributes:
|
|
249
|
+
argument: The argument the subclass describes.
|
|
250
|
+
helper: The helper that sends a parameter there, as written, for
|
|
251
|
+
messages: ``"Query()"``.
|
|
252
|
+
accepts: Where it goes and what it takes, for messages: ``"the
|
|
253
|
+
headers, which take a plain value"``.
|
|
254
|
+
body_kind: The kind of body it makes, for the one-body check, or
|
|
255
|
+
``None`` if it isn't a body.
|
|
256
|
+
send_options: The ``Send`` options it supports, by field name. Any
|
|
257
|
+
other option set on its parameter raises.
|
|
258
|
+
whole_body: A parameter going there is the whole of it, so there's
|
|
259
|
+
at most one, and it isn't sent under a key.
|
|
260
|
+
takes_text: Each value is sent as text under a key, and a model,
|
|
261
|
+
dataclass or mapping is spread into it, one value per field.
|
|
262
|
+
takes_lists: A collection of values repeats the key, as in
|
|
263
|
+
``?tag=a&tag=b``, or several files under one field.
|
|
264
|
+
lone_is_body: The only parameter going to it is the whole body, if
|
|
265
|
+
it isn't a plain value and doesn't have ``Send(embed=True)``.
|
|
266
|
+
sends_null: A parameter passed explicitly as ``None`` is sent as
|
|
267
|
+
``null``; one that isn't passed is left out. Without it, ``None``
|
|
268
|
+
is always left out.
|
|
269
|
+
streams: An iterable value is streamed, so it must match the client:
|
|
270
|
+
sync for a sync client, async for an async one.
|
|
271
|
+
keys_can_repeat: Two values under one key are both sent, so keys
|
|
272
|
+
can't clash.
|
|
273
|
+
tuples_are_values: A tuple is one value, not a collection of them.
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
argument: ClassVar[HttpxArgument]
|
|
277
|
+
helper: ClassVar[str]
|
|
278
|
+
accepts: ClassVar[str]
|
|
279
|
+
body_kind: ClassVar[str | None] = None
|
|
280
|
+
send_options: ClassVar[frozenset[str]] = frozenset()
|
|
281
|
+
whole_body: ClassVar[bool] = False
|
|
282
|
+
takes_text: ClassVar[bool] = False
|
|
283
|
+
takes_lists: ClassVar[bool] = False
|
|
284
|
+
lone_is_body: ClassVar[bool] = False
|
|
285
|
+
sends_null: ClassVar[bool] = False
|
|
286
|
+
streams: ClassVar[bool] = False
|
|
287
|
+
keys_can_repeat: ClassVar[bool] = False
|
|
288
|
+
tuples_are_values: ClassVar[bool] = False
|
|
289
|
+
|
|
290
|
+
@classmethod
|
|
291
|
+
def key(cls, name: str, alias: str | None) -> str:
|
|
292
|
+
"""Return the key a value is sent under: the alias, or else the name."""
|
|
293
|
+
return alias or name
|
|
294
|
+
|
|
295
|
+
@classmethod
|
|
296
|
+
def clash_key(cls, key: str) -> str:
|
|
297
|
+
"""Return the form of a key that's compared to find clashes: as is."""
|
|
298
|
+
return key
|
|
299
|
+
|
|
300
|
+
@classmethod
|
|
301
|
+
def check_key(cls, key: str, source: str) -> None:
|
|
302
|
+
"""Raise ``DefinitionError`` if the argument can't send under ``key``.
|
|
303
|
+
|
|
304
|
+
``source`` says where the key comes from, for messages, such as
|
|
305
|
+
``"parameter 'note'"``. Any key can be sent, by default.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
@classmethod
|
|
309
|
+
def takes_value(cls, annotation: Any) -> bool:
|
|
310
|
+
"""Return whether one value of this type can go there: a plain value.
|
|
311
|
+
|
|
312
|
+
It takes one type, not a union: the planner splits one first.
|
|
313
|
+
"""
|
|
314
|
+
return _is_plain(annotation)
|
|
315
|
+
|
|
316
|
+
@classmethod
|
|
317
|
+
def check_send(cls, send: Send, name: str) -> None:
|
|
318
|
+
"""Raise ``DefinitionError`` if ``Send`` options don't go together here.
|
|
319
|
+
|
|
320
|
+
``send_options`` says which options the argument takes; this checks how
|
|
321
|
+
they combine. Nothing to check, by default.
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
@classmethod
|
|
325
|
+
def what_fits(cls) -> str:
|
|
326
|
+
"""Return what a value can be, for messages: a plain value."""
|
|
327
|
+
plain_names = ", ".join(plain_type.__name__ for plain_type in _PLAIN_TYPES)
|
|
328
|
+
return (
|
|
329
|
+
f"A plain value is one of {plain_names}, or Any. For another type, annotate the parameter as str "
|
|
330
|
+
"and convert the value at the call."
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class UrlSpec(HttpxArgumentSpec):
|
|
335
|
+
argument = HttpxArgument.URL
|
|
336
|
+
helper = "Url()"
|
|
337
|
+
accepts = "the path, which takes a plain value"
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
class ParamsSpec(HttpxArgumentSpec):
|
|
341
|
+
argument = HttpxArgument.PARAMS
|
|
342
|
+
helper = "Query()"
|
|
343
|
+
accepts = "the query string, which takes a plain value or a collection of them"
|
|
344
|
+
takes_text = True
|
|
345
|
+
takes_lists = True
|
|
346
|
+
# exclude_unset for a parameter with a default, or a model; exclude_defaults
|
|
347
|
+
# for a spread model. Not exclude_none: a query string leaves out None.
|
|
348
|
+
send_options = frozenset({"exclude_unset", "exclude_defaults"})
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class HeadersSpec(HttpxArgumentSpec):
|
|
352
|
+
argument = HttpxArgument.HEADERS
|
|
353
|
+
helper = "Header()"
|
|
354
|
+
accepts = "the headers, which take a plain value"
|
|
355
|
+
takes_text = True
|
|
356
|
+
# exclude_unset for a parameter with a default, or a model; exclude_defaults
|
|
357
|
+
# for a spread model. Not exclude_none: headers leave out None.
|
|
358
|
+
send_options = frozenset({"exclude_unset", "exclude_defaults"})
|
|
359
|
+
|
|
360
|
+
@classmethod
|
|
361
|
+
def key(cls, name: str, alias: str | None) -> str:
|
|
362
|
+
# Python names can't have "-", so request_id is sent as request-id, as
|
|
363
|
+
# FastAPI's Header() does. An alias is sent as written.
|
|
364
|
+
return alias or name.replace("_", "-")
|
|
365
|
+
|
|
366
|
+
@classmethod
|
|
367
|
+
def clash_key(cls, key: str) -> str:
|
|
368
|
+
# Header names are case-insensitive in HTTP: X-Trace is x-trace.
|
|
369
|
+
return key.lower()
|
|
370
|
+
|
|
371
|
+
@classmethod
|
|
372
|
+
def check_key(cls, key: str, source: str) -> None:
|
|
373
|
+
# httpx2 sends header names as ASCII, and would raise UnicodeEncodeError
|
|
374
|
+
# at the call. A Python name can be any letter, so check them all.
|
|
375
|
+
if not key.isascii():
|
|
376
|
+
raise DefinitionError(
|
|
377
|
+
f"{source.capitalize()} is sent by Header() as {key!r}, which isn't ASCII, and header names must be. "
|
|
378
|
+
"Give it an ASCII alias."
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class DataSpec(HttpxArgumentSpec):
|
|
383
|
+
argument = HttpxArgument.DATA
|
|
384
|
+
helper = "Form()"
|
|
385
|
+
accepts = "the form, which takes a plain value or a collection of them"
|
|
386
|
+
takes_text = True
|
|
387
|
+
takes_lists = True
|
|
388
|
+
body_kind = "a form"
|
|
389
|
+
# json_part sends a value as a JSON part of a multipart form, as some APIs
|
|
390
|
+
# take next to files. The dump options act on a spread model or a JSON
|
|
391
|
+
# part; exclude_none on a JSON part only, since a form leaves out None.
|
|
392
|
+
send_options = frozenset({"exclude_unset", "exclude_none", "exclude_defaults", "json_part"})
|
|
393
|
+
|
|
394
|
+
@classmethod
|
|
395
|
+
def check_send(cls, send: Send, name: str) -> None:
|
|
396
|
+
if send.exclude_none is not None and not send.json_part:
|
|
397
|
+
raise DefinitionError(
|
|
398
|
+
f"Parameter {name!r} has Send(exclude_none=...), but a Form() field leaves out None already. It "
|
|
399
|
+
"applies only to a JSON part, with Send(json_part=True). Remove it."
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
class FilesSpec(HttpxArgumentSpec):
|
|
404
|
+
argument = HttpxArgument.FILES
|
|
405
|
+
helper = "File()"
|
|
406
|
+
accepts = "the form's files, which take a file or a collection of them"
|
|
407
|
+
body_kind = "a form"
|
|
408
|
+
# Several files under one field, as from <input type="file" multiple>. They
|
|
409
|
+
# go to httpx2 as a list of pairs, so two File() parameters can share a
|
|
410
|
+
# field too.
|
|
411
|
+
takes_lists = True
|
|
412
|
+
keys_can_repeat = True
|
|
413
|
+
# A tuple is one file, (filename, content...), so a list of files is a
|
|
414
|
+
# list, not a tuple.
|
|
415
|
+
tuples_are_values = True
|
|
416
|
+
|
|
417
|
+
@classmethod
|
|
418
|
+
def takes_value(cls, annotation: Any) -> bool:
|
|
419
|
+
return _is_file(annotation)
|
|
420
|
+
|
|
421
|
+
@classmethod
|
|
422
|
+
def what_fits(cls) -> str:
|
|
423
|
+
return (
|
|
424
|
+
'A file is bytes, a binary file such as open(path, "rb"), or a (filename, content[, content_type[, '
|
|
425
|
+
"headers]]) tuple, or Any. Pass text as bytes, with text.encode(), and open a path yourself."
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class ContentSpec(HttpxArgumentSpec):
|
|
430
|
+
argument = HttpxArgument.CONTENT
|
|
431
|
+
helper = "Body()"
|
|
432
|
+
accepts = "the raw body"
|
|
433
|
+
body_kind = "raw content"
|
|
434
|
+
# A Body() parameter is the whole raw body, so there's one.
|
|
435
|
+
whole_body = True
|
|
436
|
+
# httpx2 streams an iterable body: a sync Client takes only a sync one, and
|
|
437
|
+
# an AsyncClient only an async one.
|
|
438
|
+
streams = True
|
|
439
|
+
|
|
440
|
+
@classmethod
|
|
441
|
+
def takes_value(cls, annotation: Any) -> bool:
|
|
442
|
+
return _is_content(annotation)
|
|
443
|
+
|
|
444
|
+
@classmethod
|
|
445
|
+
def what_fits(cls) -> str:
|
|
446
|
+
return "The raw body is str, bytes, or an iterable or async iterable of bytes, or Any."
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class JsonSpec(HttpxArgumentSpec):
|
|
450
|
+
argument = HttpxArgument.JSON
|
|
451
|
+
helper = "Json()"
|
|
452
|
+
accepts = "the JSON body"
|
|
453
|
+
body_kind = "JSON"
|
|
454
|
+
# A lone model is the body, {"name": ...}, as in FastAPI; Send(embed=True)
|
|
455
|
+
# sends it under its name instead, {"user": {"name": ...}}.
|
|
456
|
+
lone_is_body = True
|
|
457
|
+
send_options = frozenset({"embed", "exclude_unset", "exclude_none", "exclude_defaults"})
|
|
458
|
+
# JSON has null: update(nickname=None) sends {"nickname": null}, to clear
|
|
459
|
+
# it. Query strings, headers and forms have no null.
|
|
460
|
+
sends_null = True
|
|
461
|
+
|
|
462
|
+
@classmethod
|
|
463
|
+
def takes_value(cls, annotation: Any) -> bool:
|
|
464
|
+
# Pydantic serializes any value, so a JSON field takes anything, and
|
|
465
|
+
# what_fits is never asked for.
|
|
466
|
+
return True
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# Each argument a helper can mark, to its spec. COOKIES has no helper.
|
|
470
|
+
_SPECS: dict[HttpxArgument, type[HttpxArgumentSpec]] = {
|
|
471
|
+
spec.argument: spec for spec in (UrlSpec, ParamsSpec, HeadersSpec, DataSpec, FilesSpec, ContentSpec, JsonSpec)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# --- The path -----------------------------------------------------------------
|
|
476
|
+
_PATH_SYNTAX = (
|
|
477
|
+
"A placeholder is {name}, for one path segment, or {name:path}, for a value that keeps its "
|
|
478
|
+
"slashes, where name is a parameter's name."
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _check_path_parameter(parameter: ParameterInfo, placeholder: PathPlaceholder, path_template: str) -> None:
|
|
483
|
+
"""Raise ``DefinitionError`` if a parameter can't fill its placeholder.
|
|
484
|
+
|
|
485
|
+
It must be a plain value that can't be ``None``, with no helper but
|
|
486
|
+
``Url()``, no alias, and no ``Send``.
|
|
487
|
+
"""
|
|
488
|
+
fills = f"Parameter {parameter.name!r} fills {placeholder} in the path {path_template!r}"
|
|
489
|
+
argument = parameter.httpx_argument
|
|
490
|
+
if argument is not None and argument is not HttpxArgument.URL:
|
|
491
|
+
raise DefinitionError(
|
|
492
|
+
f"{fills}, so it can't also be marked {_SPECS[argument].helper}. "
|
|
493
|
+
"Remove its helper, or rename the parameter or the placeholder."
|
|
494
|
+
)
|
|
495
|
+
field_info = parameter.clientx_field_info
|
|
496
|
+
if field_info is not None and field_info.serialization_alias not in {None, parameter.name}:
|
|
497
|
+
raise DefinitionError(
|
|
498
|
+
f"{fills}, so its Url(alias=...) has no effect: a path parameter is matched to its placeholder by "
|
|
499
|
+
"name. Remove the alias, or rename the parameter."
|
|
500
|
+
)
|
|
501
|
+
if _allows_none(parameter.annotation):
|
|
502
|
+
raise DefinitionError(
|
|
503
|
+
f"{fills}, so it can't be None: a None value would always fail at the call. Remove None from its type."
|
|
504
|
+
)
|
|
505
|
+
if not all(UrlSpec.takes_value(arm) for arm in _arms(parameter.annotation)):
|
|
506
|
+
raise DefinitionError(f"{fills}, so it must be a plain value. {UrlSpec.what_fits()}")
|
|
507
|
+
if parameter.send != Send():
|
|
508
|
+
raise DefinitionError(f"{fills}, so Send doesn't apply to it. Remove it.")
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
@dataclass(frozen=True)
|
|
512
|
+
class PathPlaceholder:
|
|
513
|
+
"""A ``{name}`` slot in the path template.
|
|
514
|
+
|
|
515
|
+
Attributes:
|
|
516
|
+
keep_slashes: ``{name:path}`` was written, so the builder sends any
|
|
517
|
+
``/`` in the value as it is, rather than encoding it as ``%2F``.
|
|
518
|
+
"""
|
|
519
|
+
|
|
520
|
+
name: str
|
|
521
|
+
keep_slashes: bool = False
|
|
522
|
+
|
|
523
|
+
def __str__(self) -> str:
|
|
524
|
+
return f"{{{self.name}:path}}" if self.keep_slashes else f"{{{self.name}}}"
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _parse_path(path_template: str) -> tuple[str | PathPlaceholder, ...]:
|
|
528
|
+
"""Split a path template into text and placeholders, in order."""
|
|
529
|
+
# Formatter().parse splits "/user/{user_id}" into (text, name, spec,
|
|
530
|
+
# conversion) chunks: ("/user/", "user_id", "", None).
|
|
531
|
+
# parse() is lazy, so list() makes it raise here, inside the try, rather
|
|
532
|
+
# than partway through the loop.
|
|
533
|
+
try:
|
|
534
|
+
chunks = list(Formatter().parse(path_template))
|
|
535
|
+
except ValueError as error:
|
|
536
|
+
raise DefinitionError(
|
|
537
|
+
f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}"
|
|
538
|
+
) from error
|
|
539
|
+
|
|
540
|
+
parts: list[str | PathPlaceholder] = []
|
|
541
|
+
for text, name, spec, conversion in chunks:
|
|
542
|
+
# Formatter turns {{ and }} into a brace in the text. ClientX has no
|
|
543
|
+
# literal braces, so any brace there is a mistake.
|
|
544
|
+
if "{" in text or "}" in text:
|
|
545
|
+
raise DefinitionError(
|
|
546
|
+
f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}"
|
|
547
|
+
)
|
|
548
|
+
if text:
|
|
549
|
+
parts.append(text)
|
|
550
|
+
if name is None:
|
|
551
|
+
continue
|
|
552
|
+
_check_placeholder(path_template, name, spec, conversion)
|
|
553
|
+
parts.append(PathPlaceholder(name, keep_slashes=spec == "path"))
|
|
554
|
+
return tuple(parts)
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _check_placeholder(path_template: str, name: str, spec: str | None, conversion: str | None) -> None:
|
|
558
|
+
"""Raise ``DefinitionError`` unless it's ``{name}`` or ``{name:path}``.
|
|
559
|
+
|
|
560
|
+
``Formatter`` only checks the braces, so ``{user-id}``, ``{a.b}``,
|
|
561
|
+
``{c[0]}``, ``{}``, ``{d!r}`` and ``{e:int}`` all reach here.
|
|
562
|
+
"""
|
|
563
|
+
if name.isidentifier() and conversion is None and spec in {"", "path"}:
|
|
564
|
+
return
|
|
565
|
+
# Rebuild the placeholder as it was written, for the message.
|
|
566
|
+
written = "{" + name + (f"!{conversion}" if conversion else "") + (f":{spec}" if spec else "") + "}"
|
|
567
|
+
raise DefinitionError(f"Path {path_template!r}: ClientX can't fill the placeholder {written}. {_PATH_SYNTAX}")
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
# --- Parameters outside the path ----------------------------------------------
|
|
571
|
+
def _helper_argument(parameter: ParameterInfo, path_template: str) -> HttpxArgument:
|
|
572
|
+
"""Return the argument a parameter outside the path goes to: its helper's.
|
|
573
|
+
|
|
574
|
+
It needs a helper that says where it goes, ``Url()`` only fits a parameter
|
|
575
|
+
that fills a placeholder, each ``Send`` option must be in its spec's
|
|
576
|
+
``send_options``, and a dump option must fit the type. An option set to
|
|
577
|
+
``False`` counts too: it can't apply there either.
|
|
578
|
+
|
|
579
|
+
Raises:
|
|
580
|
+
DefinitionError: If any of those doesn't hold.
|
|
581
|
+
"""
|
|
582
|
+
argument = parameter.httpx_argument
|
|
583
|
+
if argument is None:
|
|
584
|
+
raise DefinitionError(
|
|
585
|
+
f"Parameter {parameter.name!r} needs a helper that says where it goes: Query(), Header(), "
|
|
586
|
+
f"Json(), Body(), Form() or File(), as in {_example(parameter)}. Only a parameter named like a path "
|
|
587
|
+
"placeholder goes without one."
|
|
588
|
+
)
|
|
589
|
+
if argument is HttpxArgument.URL:
|
|
590
|
+
raise DefinitionError(
|
|
591
|
+
f"Parameter {parameter.name!r} is marked Url(), but the path {path_template!r} has no "
|
|
592
|
+
f"placeholder {{{parameter.name}}}. Add the placeholder, or remove Url()."
|
|
593
|
+
)
|
|
594
|
+
# Each Send option that's set must be one the argument's spec supports.
|
|
595
|
+
spec = _SPECS[argument]
|
|
596
|
+
for option in fields(Send):
|
|
597
|
+
if getattr(parameter.send, option.name) is None or option.name in spec.send_options:
|
|
598
|
+
continue
|
|
599
|
+
helpers = [s.helper for s in _SPECS.values() if option.name in s.send_options]
|
|
600
|
+
supported_by = helpers[0] if len(helpers) == 1 else f"{', '.join(helpers[:-1])} or {helpers[-1]}"
|
|
601
|
+
raise DefinitionError(
|
|
602
|
+
f"Parameter {parameter.name!r} has Send({option.name}=...), which applies only to a "
|
|
603
|
+
f"{supported_by} parameter, but it's marked {spec.helper}. Remove it."
|
|
604
|
+
)
|
|
605
|
+
spec.check_send(parameter.send, parameter.name)
|
|
606
|
+
_check_dump_options(parameter)
|
|
607
|
+
return argument
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _example(parameter: ParameterInfo) -> str:
|
|
611
|
+
"""Return the parameter with the helper it most likely needs, for a message.
|
|
612
|
+
|
|
613
|
+
That's ``Query()`` for a plain value and ``Json()`` for anything else.
|
|
614
|
+
"""
|
|
615
|
+
if parameter.annotation is NO_VALUE:
|
|
616
|
+
return f"{parameter.name}: Annotated[str, Query()]"
|
|
617
|
+
base = parameter.base_type
|
|
618
|
+
type_text = base.__qualname__ if isinstance(base, type) else repr(base)
|
|
619
|
+
helper = "Query()" if _all_plain(parameter.annotation) else "Json()"
|
|
620
|
+
return f"{parameter.name}: Annotated[{type_text}, {helper}]"
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# --- Send's dump options ------------------------------------------------------
|
|
624
|
+
_PYDANTIC_CLASS = (
|
|
625
|
+
"a pydantic model or pydantic dataclass (pydantic doesn't apply it to a stdlib dataclass: make it a "
|
|
626
|
+
"pydantic.dataclasses.dataclass)"
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _is_model(cls: type[Any]) -> bool:
|
|
631
|
+
return issubclass(cls, BaseModel)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _is_model_or_pydantic_dataclass(cls: type[Any]) -> bool:
|
|
635
|
+
return issubclass(cls, BaseModel) or is_pydantic_dataclass(cls)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# Each field-only dump option, the classes whose fields it affects, and those in
|
|
639
|
+
# words, for messages. Dumping a value by its own type, pydantic silently
|
|
640
|
+
# ignores them on a stdlib dataclass and a dict, so an option on a type it
|
|
641
|
+
# can't affect raises instead. exclude_unset isn't here: it also leaves out the
|
|
642
|
+
# parameter itself, so _check_dump_options checks it on its own.
|
|
643
|
+
_DUMP_OPTIONS: dict[str, tuple[Callable[[type[Any]], bool], str]] = {
|
|
644
|
+
"exclude_none": (_is_model_or_pydantic_dataclass, _PYDANTIC_CLASS),
|
|
645
|
+
"exclude_defaults": (_is_model_or_pydantic_dataclass, _PYDANTIC_CLASS),
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _check_dump_options(parameter: ParameterInfo) -> None:
|
|
650
|
+
"""Raise ``DefinitionError`` for a dump option that would do nothing.
|
|
651
|
+
|
|
652
|
+
``exclude_none`` and ``exclude_defaults`` affect the fields of some classes
|
|
653
|
+
only (``_DUMP_OPTIONS``), so the type must have one, at any depth:
|
|
654
|
+
``list[User]`` counts. ``exclude_unset`` leaves out the parameter when it
|
|
655
|
+
isn't passed, and a pydantic model's unset fields, so it needs a default
|
|
656
|
+
other than ``None``, which is left out anyway, or a model.
|
|
657
|
+
"""
|
|
658
|
+
for option, (affects, described) in _DUMP_OPTIONS.items():
|
|
659
|
+
if getattr(parameter.send, option) is None:
|
|
660
|
+
continue
|
|
661
|
+
if not _contains_class(parameter.annotation, affects, frozenset()):
|
|
662
|
+
hint = (
|
|
663
|
+
" To leave out the parameter itself when the caller doesn't pass it, use Send(exclude_unset=True)."
|
|
664
|
+
if option == "exclude_defaults"
|
|
665
|
+
else ""
|
|
666
|
+
)
|
|
667
|
+
raise DefinitionError(
|
|
668
|
+
f"Parameter {parameter.name!r} has Send({option}=...), which leaves out fields of "
|
|
669
|
+
f"{described}, but its type has none. Remove it.{hint}"
|
|
670
|
+
)
|
|
671
|
+
if (
|
|
672
|
+
parameter.send.exclude_unset is not None
|
|
673
|
+
and (parameter.default is NO_VALUE or parameter.default is None)
|
|
674
|
+
and not _contains_class(parameter.annotation, _is_model, frozenset())
|
|
675
|
+
):
|
|
676
|
+
why = (
|
|
677
|
+
"it has no default, so it's always passed"
|
|
678
|
+
if parameter.default is NO_VALUE
|
|
679
|
+
else "its default is None, which is left out anyway"
|
|
680
|
+
)
|
|
681
|
+
raise DefinitionError(
|
|
682
|
+
f"Parameter {parameter.name!r} has Send(exclude_unset=...), but {why}, and its type has no pydantic "
|
|
683
|
+
"model, whose unset fields it would leave out. Give it another default, or remove it."
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def _dump_options(parameter: ParameterInfo) -> DumpOptions:
|
|
688
|
+
"""Return the parameter's ``Send`` dump options, for the plan."""
|
|
689
|
+
send = parameter.send
|
|
690
|
+
return DumpOptions(
|
|
691
|
+
exclude_unset=bool(send.exclude_unset),
|
|
692
|
+
exclude_none=bool(send.exclude_none),
|
|
693
|
+
exclude_defaults=bool(send.exclude_defaults),
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _contains_class(annotation: Any, wanted: Callable[[type[Any]], bool], seen: frozenset[TypeAliasType]) -> bool:
|
|
698
|
+
"""Return whether ``annotation``, or a type inside it, is a wanted class.
|
|
699
|
+
|
|
700
|
+
``seen`` holds the ``type`` aliases already expanded, as in ``_contains``,
|
|
701
|
+
so one that contains itself is expanded only once.
|
|
702
|
+
"""
|
|
703
|
+
alias = annotation if isinstance(annotation, TypeAliasType) else get_origin(annotation)
|
|
704
|
+
if isinstance(alias, TypeAliasType):
|
|
705
|
+
if alias in seen:
|
|
706
|
+
return False
|
|
707
|
+
seen |= {alias}
|
|
708
|
+
base, _ = unwrap_annotated(annotation)
|
|
709
|
+
cls = _class_of(base)
|
|
710
|
+
if cls is not None and wanted(cls):
|
|
711
|
+
return True
|
|
712
|
+
return any(_contains_class(arg, wanted, seen) for arg in get_args(base))
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
# --- Helpers and Send nested in a type ----------------------------------------
|
|
716
|
+
def _check_nested(parameter: ParameterInfo) -> None:
|
|
717
|
+
"""Raise ``DefinitionError`` if a helper or ``Send`` is inside the type.
|
|
718
|
+
|
|
719
|
+
ClientX reads both only in the outermost ``Annotated``, so the helper in
|
|
720
|
+
``Annotated[str, Header()] | None`` would be ignored.
|
|
721
|
+
"""
|
|
722
|
+
# base_type is the type without the outermost Annotated, which
|
|
723
|
+
# ParameterInfo has already read, so only what's inside it is searched.
|
|
724
|
+
inside = get_args(parameter.base_type)
|
|
725
|
+
if any(_contains(arg, _is_helper, frozenset()) for arg in inside):
|
|
726
|
+
raise DefinitionError(
|
|
727
|
+
f"Parameter {parameter.name!r} has a helper inside its type. ClientX reads a helper only "
|
|
728
|
+
"in the outermost Annotated, so move it there: for example, Annotated[str | None, Header()] "
|
|
729
|
+
"rather than Annotated[str, Header()] | None."
|
|
730
|
+
)
|
|
731
|
+
if any(_contains(arg, _is_send, frozenset()) for arg in inside):
|
|
732
|
+
raise DefinitionError(
|
|
733
|
+
f"Parameter {parameter.name!r} has a Send inside its type. ClientX reads Send only in the "
|
|
734
|
+
"outermost Annotated, so move it there: for example, Annotated[list[str] | None, Json(), "
|
|
735
|
+
"Send(embed=True)] rather than Annotated[list[str], Json(), Send(embed=True)] | None."
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _contains(annotation: Any, wanted: Callable[[object], bool], seen: frozenset[TypeAliasType]) -> bool:
|
|
740
|
+
"""Return whether ``annotation``, or a type inside it, has ``wanted``.
|
|
741
|
+
|
|
742
|
+
``seen`` holds the ``type`` aliases already expanded on the way here, so one
|
|
743
|
+
that contains itself, such as ``type Value = dict[str, Value] | str``, is
|
|
744
|
+
expanded only once.
|
|
745
|
+
"""
|
|
746
|
+
alias = annotation if isinstance(annotation, TypeAliasType) else get_origin(annotation)
|
|
747
|
+
if isinstance(alias, TypeAliasType):
|
|
748
|
+
if alias in seen:
|
|
749
|
+
return False
|
|
750
|
+
seen |= {alias}
|
|
751
|
+
# unwrap_annotated expands a type alias too, so metadata inside one counts.
|
|
752
|
+
base, metadata = unwrap_annotated(annotation)
|
|
753
|
+
if any(wanted(meta) for meta in metadata):
|
|
754
|
+
return True
|
|
755
|
+
return any(_contains(arg, wanted, seen) for arg in get_args(base))
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _is_helper(meta: object) -> bool:
|
|
759
|
+
return get_httpx_argument(meta) is not None
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _is_send(meta: object) -> bool:
|
|
763
|
+
return isinstance(meta, Send)
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
# --- Serializers in a parameter's type ----------------------------------------
|
|
767
|
+
def _check_serializers(parameter: ParameterInfo) -> None:
|
|
768
|
+
"""Raise ``DefinitionError`` for a pydantic serializer in the type.
|
|
769
|
+
|
|
770
|
+
ClientX sends a value by its own type, at the call, so a
|
|
771
|
+
``PlainSerializer`` or ``WrapSerializer`` in the parameter's annotation
|
|
772
|
+
would be ignored silently. A model's own serializers do run.
|
|
773
|
+
"""
|
|
774
|
+
if _contains(parameter.annotation, _is_serializer, frozenset()):
|
|
775
|
+
raise DefinitionError(
|
|
776
|
+
f"Parameter {parameter.name!r} has a pydantic serializer in its type, but ClientX sends a value by its "
|
|
777
|
+
"own type, so the serializer wouldn't run. Convert the value at the call, or make it a field of a "
|
|
778
|
+
"model, where its serializers apply."
|
|
779
|
+
)
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _is_serializer(meta: object) -> bool:
|
|
783
|
+
return isinstance(meta, PlainSerializer | WrapSerializer)
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
# --- Defaults inside a helper -------------------------------------------------
|
|
787
|
+
def _check_helper_default(parameter: ParameterInfo) -> None:
|
|
788
|
+
"""Raise ``DefinitionError`` if the helper has a default.
|
|
789
|
+
|
|
790
|
+
The helpers take ``pydantic.Field``'s arguments, so ``Query(1)``,
|
|
791
|
+
``Query(default=1)`` and ``Query(default_factory=list)`` all set one, but
|
|
792
|
+
ClientX reads the default after ``=``, as Python does.
|
|
793
|
+
"""
|
|
794
|
+
field_info = parameter.clientx_field_info
|
|
795
|
+
if field_info is None:
|
|
796
|
+
return
|
|
797
|
+
if field_info.default is not PydanticUndefined or field_info.default_factory is not None:
|
|
798
|
+
raise DefinitionError(
|
|
799
|
+
f"Parameter {parameter.name!r} has a default inside its helper, where ClientX doesn't read it. "
|
|
800
|
+
"Put the default after = instead, as in page: Annotated[int, Query()] = 1."
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
# --- Helpers and Send on a model's fields -------------------------------------
|
|
805
|
+
def _check_model_fields(parameter: ParameterInfo) -> None:
|
|
806
|
+
"""Raise ``DefinitionError`` if a model's field has a helper or ``Send``.
|
|
807
|
+
|
|
808
|
+
The parameter's helper decides where the whole model goes, so ClientX
|
|
809
|
+
doesn't read either on a field. Each arm of a union is checked, so
|
|
810
|
+
``Filters | None`` counts.
|
|
811
|
+
"""
|
|
812
|
+
for arm in _arms(parameter.annotation):
|
|
813
|
+
cls = _class_of(arm)
|
|
814
|
+
if cls is None or not issubclass(cls, BaseModel):
|
|
815
|
+
continue
|
|
816
|
+
for field_name, field_info in cls.model_fields.items():
|
|
817
|
+
if _is_helper(field_info):
|
|
818
|
+
raise DefinitionError(
|
|
819
|
+
f"Field {field_name!r} of {cls.__name__} has a clientx.arguments helper, but ClientX reads "
|
|
820
|
+
f"helpers only on endpoint parameters. Put the helper on parameter {parameter.name!r} "
|
|
821
|
+
f"instead, as in Annotated[{cls.__name__}, Query()]: all of the model's fields then go there."
|
|
822
|
+
)
|
|
823
|
+
if any(_is_send(meta) for meta in field_info.metadata):
|
|
824
|
+
raise DefinitionError(
|
|
825
|
+
f"Field {field_name!r} of {cls.__name__} has a Send, but ClientX reads Send only on "
|
|
826
|
+
f"endpoint parameters. Put it on parameter {parameter.name!r} instead."
|
|
827
|
+
)
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
# --- Parameters sent under a key ----------------------------------------------
|
|
831
|
+
def _plan_keyed(parameter: ParameterInfo, argument: HttpxArgument) -> PlannedParameter | SpreadParameter:
|
|
832
|
+
"""Return where a parameter sent under a key goes, and its key.
|
|
833
|
+
|
|
834
|
+
A value the argument's spec takes is sent once. If the spec
|
|
835
|
+
``takes_lists``, a collection of them repeats the key, and a type that
|
|
836
|
+
takes either, such as ``str | list[str]``, is decided at the call. A
|
|
837
|
+
model, dataclass or mapping is spread, one value per field or item, if the
|
|
838
|
+
spec ``takes_text``. Anything else raises ``DefinitionError``, saying what
|
|
839
|
+
fits.
|
|
840
|
+
"""
|
|
841
|
+
spec = _SPECS[argument]
|
|
842
|
+
field_info = parameter.clientx_field_info
|
|
843
|
+
alias = field_info.serialization_alias if field_info is not None else None
|
|
844
|
+
key = spec.key(parameter.name, alias)
|
|
845
|
+
dump = _dump_options(parameter)
|
|
846
|
+
# Send(exclude_none=True) leaves out None, so it isn't sent as null.
|
|
847
|
+
sends_null = spec.sends_null and not dump.exclude_none
|
|
848
|
+
only_if_passed = dump.exclude_unset
|
|
849
|
+
if parameter.send.json_part:
|
|
850
|
+
# Any value pydantic can serialize: it's sent as JSON, not as text.
|
|
851
|
+
return PlannedParameter(parameter.name, argument, key, only_if_passed=only_if_passed, json_part=True, dump=dump)
|
|
852
|
+
arms = _arms(parameter.annotation)
|
|
853
|
+
if all(spec.takes_value(arm) for arm in arms):
|
|
854
|
+
return PlannedParameter(
|
|
855
|
+
parameter.name, argument, key, sends_null=sends_null, only_if_passed=only_if_passed, dump=dump
|
|
856
|
+
)
|
|
857
|
+
if spec.takes_lists and all(spec.takes_value(arm) or _is_list_of(arm, spec) for arm in arms):
|
|
858
|
+
return PlannedParameter(parameter.name, argument, key, many=True, only_if_passed=only_if_passed)
|
|
859
|
+
if spec.takes_text and len(arms) == 1 and _has_fields(arms[0]):
|
|
860
|
+
return _plan_spread(parameter, argument, arms[0])
|
|
861
|
+
raise DefinitionError(
|
|
862
|
+
f"Parameter {parameter.name!r} is marked {spec.helper}, so it goes to {spec.accepts}. {spec.what_fits()}"
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def _plan_spread(parameter: ParameterInfo, argument: HttpxArgument, annotation: Any) -> SpreadParameter:
|
|
867
|
+
"""Plan a model, dataclass or mapping parameter spread into ``argument``.
|
|
868
|
+
|
|
869
|
+
Each field, computed fields included, is sent under the key the
|
|
870
|
+
argument's spec gives its alias or attribute name, so a header field's
|
|
871
|
+
``_`` becomes ``-`` too. A mapping's items are sent under their own keys,
|
|
872
|
+
as they are, and so is what a model with its own model serializer dumps:
|
|
873
|
+
its keys exist only at the call. Each field, or the mapping's value type,
|
|
874
|
+
must be something the argument takes, as a parameter must, so a nested
|
|
875
|
+
model raises ``DefinitionError``.
|
|
876
|
+
"""
|
|
877
|
+
spec = _SPECS[argument]
|
|
878
|
+
dump = _dump_options(parameter)
|
|
879
|
+
cls = cast("type[Any]", _class_of(annotation))
|
|
880
|
+
if issubclass(cls, Mapping):
|
|
881
|
+
# dict[str, int] lists the key and value types; a bare dict, neither.
|
|
882
|
+
type_args = get_args(annotation)
|
|
883
|
+
value_type = type_args[1] if len(type_args) == 2 else Any
|
|
884
|
+
if not _fits(value_type, spec):
|
|
885
|
+
raise DefinitionError(
|
|
886
|
+
f"Parameter {parameter.name!r} is marked {spec.helper}, so each item of the mapping goes to "
|
|
887
|
+
f"{spec.accepts}. Its value type isn't one."
|
|
888
|
+
)
|
|
889
|
+
return SpreadParameter(parameter.name, argument, many=spec.takes_lists, only_if_passed=dump.exclude_unset)
|
|
890
|
+
if _has_model_serializer(cls):
|
|
891
|
+
# It decides its own keys, so what it dumps is sent, as a mapping is.
|
|
892
|
+
return SpreadParameter(
|
|
893
|
+
parameter.name, argument, many=spec.takes_lists, only_if_passed=dump.exclude_unset, dump=dump
|
|
894
|
+
)
|
|
895
|
+
keys: list[tuple[str, str]] = []
|
|
896
|
+
for attribute, (field_type, alias) in _fields_of(cls).items():
|
|
897
|
+
if not _fits(field_type, spec):
|
|
898
|
+
raise DefinitionError(
|
|
899
|
+
f"Parameter {parameter.name!r} is marked {spec.helper}, so each field of {cls.__name__} goes to "
|
|
900
|
+
f"{spec.accepts}. Field {attribute!r} isn't one."
|
|
901
|
+
)
|
|
902
|
+
keys.append((attribute, spec.key(attribute, alias)))
|
|
903
|
+
return SpreadParameter(
|
|
904
|
+
parameter.name, argument, tuple(keys), many=spec.takes_lists, only_if_passed=dump.exclude_unset, dump=dump
|
|
905
|
+
)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _fields_of(cls: type[Any]) -> dict[str, tuple[Any, str | None]]:
|
|
909
|
+
"""Return each field's type and serialization alias, by attribute name.
|
|
910
|
+
|
|
911
|
+
A model's computed fields count too: they're dumped like fields.
|
|
912
|
+
"""
|
|
913
|
+
if issubclass(cls, BaseModel):
|
|
914
|
+
model_fields = {name: (info.annotation, info.serialization_alias) for name, info in cls.model_fields.items()}
|
|
915
|
+
computed = {name: (info.return_type, info.alias) for name, info in cls.model_computed_fields.items()}
|
|
916
|
+
return model_fields | computed
|
|
917
|
+
if is_pydantic_dataclass(cls):
|
|
918
|
+
return {name: (info.annotation, info.serialization_alias) for name, info in cls.__pydantic_fields__.items()}
|
|
919
|
+
# A standard library dataclass: its fields have no aliases.
|
|
920
|
+
hints = get_type_hints(cls)
|
|
921
|
+
return {field.name: (hints.get(field.name, Any), None) for field in fields(cls)}
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def _has_model_serializer(cls: type[Any]) -> bool:
|
|
925
|
+
"""Return whether a model or pydantic dataclass has a model serializer."""
|
|
926
|
+
decorators = getattr(cls, "__pydantic_decorators__", None)
|
|
927
|
+
return decorators is not None and bool(decorators.model_serializers)
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _fits(annotation: Any, spec: type[HttpxArgumentSpec]) -> bool:
|
|
931
|
+
"""Return whether a value of this type can go to the spec's argument.
|
|
932
|
+
|
|
933
|
+
That's a value the spec takes, or, if it ``takes_lists``, a collection of
|
|
934
|
+
them, or a type that takes either.
|
|
935
|
+
"""
|
|
936
|
+
return all(spec.takes_value(arm) or (spec.takes_lists and _is_list_of(arm, spec)) for arm in _arms(annotation))
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def _check_keys(planned: Sequence[PlannedParameter | SpreadParameter]) -> None:
|
|
940
|
+
"""Raise ``DefinitionError`` for a key that can't be sent or that clashes.
|
|
941
|
+
|
|
942
|
+
Each key is checked by its argument's spec, as a header name must be ASCII.
|
|
943
|
+
Two values going to one argument under one key clash: httpx2 would keep
|
|
944
|
+
only one of them, silently. Only keys known now count: a mapping's keys
|
|
945
|
+
exist only at the call, so a clash with one is the caller's to avoid. An
|
|
946
|
+
argument whose spec ``keys_can_repeat``, such as files, sends both, so it
|
|
947
|
+
can't clash.
|
|
948
|
+
"""
|
|
949
|
+
# Each (argument, clash key) seen so far, to where it came from and its key.
|
|
950
|
+
sources: dict[tuple[HttpxArgument, str], tuple[str, str]] = {}
|
|
951
|
+
for item in planned:
|
|
952
|
+
if isinstance(item, PlannedParameter):
|
|
953
|
+
keyed = [(item.key, f"parameter {item.name!r}")]
|
|
954
|
+
elif item.keys is not None:
|
|
955
|
+
keyed = [(key, f"field {attribute!r} of parameter {item.name!r}") for attribute, key in item.keys]
|
|
956
|
+
else:
|
|
957
|
+
continue
|
|
958
|
+
spec = _SPECS[item.httpx_argument]
|
|
959
|
+
for key, source in keyed:
|
|
960
|
+
spec.check_key(key, source)
|
|
961
|
+
if spec.keys_can_repeat:
|
|
962
|
+
continue
|
|
963
|
+
for key, source in keyed:
|
|
964
|
+
where = (item.httpx_argument, spec.clash_key(key))
|
|
965
|
+
if where not in sources:
|
|
966
|
+
sources[where] = (source, key)
|
|
967
|
+
continue
|
|
968
|
+
earlier_source, earlier_key = sources[where]
|
|
969
|
+
sent_as = f"both sent as {key!r}" if key == earlier_key else f"sent as {earlier_key!r} and {key!r}"
|
|
970
|
+
raise DefinitionError(
|
|
971
|
+
f"{earlier_source.capitalize()} and {source} are {sent_as} by {spec.helper}, the same key, so "
|
|
972
|
+
"one would be lost. Rename one, or give it an alias."
|
|
973
|
+
)
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
# --- The body -----------------------------------------------------------------
|
|
977
|
+
def _find_lone_body(parameters: Sequence[ParameterInfo]) -> ParameterInfo | None:
|
|
978
|
+
"""Return the parameter that's the whole body by the lone rule, or ``None``.
|
|
979
|
+
|
|
980
|
+
That's the only parameter going to an argument whose spec has
|
|
981
|
+
``lone_is_body`` (JSON), unless it has ``Send(embed=True)``, or it's a
|
|
982
|
+
plain value, which is sent under its name. ``Any`` isn't plain here: it's
|
|
983
|
+
the whole body, like a model. Adding a second ``Json()`` parameter moves
|
|
984
|
+
the first under its name, as FastAPI does.
|
|
985
|
+
"""
|
|
986
|
+
candidates = [p for p in parameters if p.httpx_argument is not None and _SPECS[p.httpx_argument].lone_is_body]
|
|
987
|
+
if len(candidates) != 1:
|
|
988
|
+
return None
|
|
989
|
+
(parameter,) = candidates
|
|
990
|
+
arms = _arms(parameter.annotation)
|
|
991
|
+
if parameter.send.embed or (_all_plain(parameter.annotation) and Any not in arms):
|
|
992
|
+
return None
|
|
993
|
+
return parameter
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def _plan_body(parameter: ParameterInfo, argument: HttpxArgument, *, is_async: bool) -> PlannedParameter:
|
|
997
|
+
"""Plan a parameter that's the whole body: ``Body()``, or a lone ``Json()``.
|
|
998
|
+
|
|
999
|
+
Its value must be one the argument's spec takes, and a stream must match
|
|
1000
|
+
the client, or ``DefinitionError`` is raised. ``None`` means no body, never
|
|
1001
|
+
``null``, for JSON too: an API that takes an object rarely wants the body
|
|
1002
|
+
``null``.
|
|
1003
|
+
"""
|
|
1004
|
+
spec = _SPECS[argument]
|
|
1005
|
+
if not all(spec.takes_value(arm) for arm in _arms(parameter.annotation)):
|
|
1006
|
+
raise DefinitionError(
|
|
1007
|
+
f"Parameter {parameter.name!r} is marked {spec.helper}, so it goes to {spec.accepts}. {spec.what_fits()}"
|
|
1008
|
+
)
|
|
1009
|
+
if spec.streams:
|
|
1010
|
+
_check_stream_kind(parameter, spec, is_async=is_async)
|
|
1011
|
+
# The key isn't used: the value is the whole body.
|
|
1012
|
+
dump = _dump_options(parameter)
|
|
1013
|
+
return PlannedParameter(parameter.name, argument, key=parameter.name, only_if_passed=dump.exclude_unset, dump=dump)
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
def _check_stream_kind(parameter: ParameterInfo, spec: type[HttpxArgumentSpec], *, is_async: bool) -> None:
|
|
1017
|
+
"""Raise ``DefinitionError`` if a streamed body doesn't match the client.
|
|
1018
|
+
|
|
1019
|
+
httpx2 raises ``RuntimeError`` at the call otherwise: a sync ``Client``
|
|
1020
|
+
can't send an async iterable, and an ``AsyncClient`` can't send a sync one,
|
|
1021
|
+
a ``list[bytes]`` included. ``str``, ``bytes`` and ``Any`` fit both.
|
|
1022
|
+
"""
|
|
1023
|
+
for arm in _arms(parameter.annotation):
|
|
1024
|
+
cls = _class_of(arm)
|
|
1025
|
+
if cls is None or issubclass(cls, str | bytes):
|
|
1026
|
+
continue
|
|
1027
|
+
if is_async and issubclass(cls, Iterable):
|
|
1028
|
+
raise DefinitionError(
|
|
1029
|
+
f"Parameter {parameter.name!r} is marked {spec.helper} with a sync iterable, but the endpoint is "
|
|
1030
|
+
"async, and an async client streams only an async iterable of bytes. Make it an "
|
|
1031
|
+
"AsyncIterator[bytes], or bytes."
|
|
1032
|
+
)
|
|
1033
|
+
if not is_async and issubclass(cls, AsyncIterable):
|
|
1034
|
+
raise DefinitionError(
|
|
1035
|
+
f"Parameter {parameter.name!r} is marked {spec.helper} with an async iterable, but the endpoint is "
|
|
1036
|
+
"sync, and a sync client streams only an iterable of bytes. Make it an Iterator[bytes], or bytes, "
|
|
1037
|
+
"or move the endpoint to an AsyncClientX."
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
def _check_one_body(parameters: Sequence[ParameterInfo]) -> None:
|
|
1042
|
+
"""Raise ``DefinitionError`` if the parameters mix kinds of body.
|
|
1043
|
+
|
|
1044
|
+
httpx2 sends one body, and given several, it silently drops the others.
|
|
1045
|
+
"""
|
|
1046
|
+
body_parameters: list[tuple[str, str]] = []
|
|
1047
|
+
for parameter in parameters:
|
|
1048
|
+
if parameter.httpx_argument is None: # A path parameter without Url().
|
|
1049
|
+
continue
|
|
1050
|
+
kind = _SPECS[parameter.httpx_argument].body_kind
|
|
1051
|
+
if kind is not None:
|
|
1052
|
+
body_parameters.append((parameter.name, kind))
|
|
1053
|
+
if len({kind for _, kind in body_parameters}) > 1:
|
|
1054
|
+
listed = ", ".join(f"{name!r} ({kind})" for name, kind in body_parameters)
|
|
1055
|
+
raise DefinitionError(
|
|
1056
|
+
f"The parameters make more than one kind of body: {listed}. A request has one body: JSON, "
|
|
1057
|
+
"the raw content of one Body() parameter, or a form of Form() and File() parameters."
|
|
1058
|
+
)
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def _check_one_whole_body(parameters: Sequence[ParameterInfo]) -> None:
|
|
1062
|
+
"""Raise ``DefinitionError`` if two parameters go where only one can.
|
|
1063
|
+
|
|
1064
|
+
That's an argument whose spec has ``whole_body``, such as ``content``: a
|
|
1065
|
+
``Body()`` parameter is the whole raw body.
|
|
1066
|
+
"""
|
|
1067
|
+
names_by_argument: dict[HttpxArgument, list[str]] = {}
|
|
1068
|
+
for parameter in parameters:
|
|
1069
|
+
if parameter.httpx_argument is not None and _SPECS[parameter.httpx_argument].whole_body:
|
|
1070
|
+
names_by_argument.setdefault(parameter.httpx_argument, []).append(repr(parameter.name))
|
|
1071
|
+
for argument, names in names_by_argument.items():
|
|
1072
|
+
if len(names) > 1:
|
|
1073
|
+
raise DefinitionError(
|
|
1074
|
+
f"Parameters {', '.join(names)} are all marked {_SPECS[argument].helper}, but an endpoint "
|
|
1075
|
+
"can have only one."
|
|
1076
|
+
)
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
# --- What a type is -----------------------------------------------------------
|
|
1080
|
+
# The plain-value allow-list: each has one defined text form. A subclass counts
|
|
1081
|
+
# too, so bool (an int), datetime (a date) and any Enum are in.
|
|
1082
|
+
_PLAIN_TYPES = (str, int, float, bool, Enum, date, datetime, time, UUID, Decimal, bytes)
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def _is_plain(annotation: Any) -> bool:
|
|
1086
|
+
"""Return whether a value of this type is sent as one piece of text.
|
|
1087
|
+
|
|
1088
|
+
It is if it's on the allow-list (a ``NewType`` of one counts), a
|
|
1089
|
+
``Literal`` of values on it, or ``Any`` or no annotation, the escape hatch.
|
|
1090
|
+
It takes one type: ``_all_plain`` splits a union first.
|
|
1091
|
+
"""
|
|
1092
|
+
if annotation is Any or annotation is NO_VALUE:
|
|
1093
|
+
return True
|
|
1094
|
+
if get_origin(annotation) is Literal:
|
|
1095
|
+
# Literal["asc", "desc"]: each value is plain. None is left out.
|
|
1096
|
+
return all(value is None or isinstance(value, _PLAIN_TYPES) for value in get_args(annotation))
|
|
1097
|
+
cls = _class_of(annotation)
|
|
1098
|
+
return cls is not None and issubclass(cls, _PLAIN_TYPES)
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
# How deep _arms follows unions inside unions, so a type alias that contains
|
|
1102
|
+
# itself, such as ``type U = int | U``, can't recurse forever.
|
|
1103
|
+
_MAX_UNION_DEPTH = 100
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def _arms(annotation: Any, depth: int = 0) -> list[Any]:
|
|
1107
|
+
"""Return the types a value of ``annotation`` can have, without ``None``.
|
|
1108
|
+
|
|
1109
|
+
For a union, they're its members, each without ``Annotated`` or a ``type``
|
|
1110
|
+
alias, and a union inside a union is flattened: ``int | (str | None)`` gives
|
|
1111
|
+
``[int, str]``. A type that isn't a union is the only one.
|
|
1112
|
+
"""
|
|
1113
|
+
base, _ = unwrap_annotated(annotation)
|
|
1114
|
+
if base is NoneType:
|
|
1115
|
+
return []
|
|
1116
|
+
# Union is Optional[int] and Union[int, str]; UnionType is int | str.
|
|
1117
|
+
if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH:
|
|
1118
|
+
return [base]
|
|
1119
|
+
return [arm for member in get_args(base) for arm in _arms(member, depth + 1)]
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _all_plain(annotation: Any) -> bool:
|
|
1123
|
+
return all(_is_plain(arm) for arm in _arms(annotation))
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def _allows_none(annotation: Any, depth: int = 0) -> bool:
|
|
1127
|
+
"""Return whether ``None`` is one of the types a value can have.
|
|
1128
|
+
|
|
1129
|
+
``_arms`` drops ``None``, so this is how to ask about it: ``int | None``,
|
|
1130
|
+
``Optional[int]`` and ``Literal["a", None]`` allow it.
|
|
1131
|
+
"""
|
|
1132
|
+
base, _ = unwrap_annotated(annotation)
|
|
1133
|
+
if base is NoneType or base is None:
|
|
1134
|
+
return True
|
|
1135
|
+
if get_origin(base) is Literal:
|
|
1136
|
+
return None in get_args(base)
|
|
1137
|
+
if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH:
|
|
1138
|
+
return False
|
|
1139
|
+
return any(_allows_none(member, depth + 1) for member in get_args(base))
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
def _class_of(annotation: Any) -> type[Any] | None:
|
|
1143
|
+
"""Return the class a type stands for, or ``None`` if it isn't one.
|
|
1144
|
+
|
|
1145
|
+
``list[str]`` stands for ``list``, and ``NewType("UserId", int)`` for
|
|
1146
|
+
``int``. ``Literal["a"]`` and a ``TypeVar``, for example, aren't classes.
|
|
1147
|
+
"""
|
|
1148
|
+
# A NewType isn't a class; the type it's made from is.
|
|
1149
|
+
while hasattr(annotation, "__supertype__"):
|
|
1150
|
+
annotation = annotation.__supertype__
|
|
1151
|
+
# get_origin gives list for list[str], and None for a plain class like int.
|
|
1152
|
+
cls: object = get_origin(annotation) or annotation
|
|
1153
|
+
return cast("type[Any]", cls) if isinstance(cls, type) else None
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
def _has_fields(annotation: Any) -> bool:
|
|
1157
|
+
"""Return whether the type is a model, dataclass or mapping: has fields."""
|
|
1158
|
+
cls = _class_of(annotation)
|
|
1159
|
+
return cls is not None and (issubclass(cls, BaseModel | Mapping) or is_dataclass(cls))
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def _is_list_of(annotation: Any, spec: type[HttpxArgumentSpec]) -> bool:
|
|
1163
|
+
"""Return whether the type is a collection of values the spec takes.
|
|
1164
|
+
|
|
1165
|
+
Any collection but a mapping counts: ``list``, ``tuple``, ``set`` and
|
|
1166
|
+
``frozenset``, but not a tuple where the spec says ``tuples_are_values``.
|
|
1167
|
+
A set's order can change from run to run, and the request with it.
|
|
1168
|
+
``str``, ``bytes`` and ``bytearray`` are collections too, but of
|
|
1169
|
+
characters and numbers, not of values, so they don't count.
|
|
1170
|
+
"""
|
|
1171
|
+
cls = _class_of(annotation)
|
|
1172
|
+
if cls is None or issubclass(cls, str | bytes | bytearray | Mapping) or not issubclass(cls, Collection):
|
|
1173
|
+
return False
|
|
1174
|
+
if spec.tuples_are_values and issubclass(cls, tuple):
|
|
1175
|
+
return False
|
|
1176
|
+
# tuple[str, ...] lists str and then Ellipsis. A bare list has no item
|
|
1177
|
+
# types, so its items count as Any.
|
|
1178
|
+
item_types = [item for item in get_args(annotation) if item is not Ellipsis]
|
|
1179
|
+
return all(spec.takes_value(arm) for item in item_types for arm in _arms(item))
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
def _is_file(annotation: Any) -> bool:
|
|
1183
|
+
"""Return whether a value of this type is one file httpx2 can send.
|
|
1184
|
+
|
|
1185
|
+
That's file content (``bytes`` or a binary file), a ``(filename,
|
|
1186
|
+
content[, content_type[, headers]])`` tuple, or ``Any``. Not ``str``:
|
|
1187
|
+
httpx2 would send the string as the file's content, so ``"report.pdf"``
|
|
1188
|
+
would upload that text, named ``upload``.
|
|
1189
|
+
"""
|
|
1190
|
+
cls = _class_of(annotation)
|
|
1191
|
+
if cls is not None and issubclass(cls, tuple):
|
|
1192
|
+
return _is_file_tuple(annotation)
|
|
1193
|
+
return _is_file_content(annotation)
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def _is_file_content(annotation: Any) -> bool:
|
|
1197
|
+
"""Return whether the type is ``bytes``, a binary file, or ``Any``."""
|
|
1198
|
+
if annotation is Any or annotation is NO_VALUE:
|
|
1199
|
+
return True
|
|
1200
|
+
cls = _class_of(annotation)
|
|
1201
|
+
return cls is not None and (issubclass(cls, bytes) or _is_binary_file(cls, annotation))
|
|
1202
|
+
|
|
1203
|
+
|
|
1204
|
+
def _is_binary_file(cls: type[Any], annotation: Any) -> bool:
|
|
1205
|
+
"""Return whether the type, whose class is ``cls``, is a file of bytes.
|
|
1206
|
+
|
|
1207
|
+
``IO[bytes]`` and ``BinaryIO`` are; so are ``io.BytesIO`` and what
|
|
1208
|
+
``open(path, "rb")`` returns. ``IO[str]``, ``TextIO`` and a text file
|
|
1209
|
+
aren't. A bare ``IO`` has no item type, so it counts as ``Any``.
|
|
1210
|
+
"""
|
|
1211
|
+
if issubclass(cls, IO):
|
|
1212
|
+
type_args = get_args(annotation)
|
|
1213
|
+
return not issubclass(cls, TextIO) and (not type_args or type_args[0] is bytes or type_args[0] is Any)
|
|
1214
|
+
return issubclass(cls, io.RawIOBase | io.BufferedIOBase)
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
def _is_file_tuple(annotation: Any) -> bool:
|
|
1218
|
+
"""Return whether the type is ``(filename, content[, type[, headers]])``.
|
|
1219
|
+
|
|
1220
|
+
The filename and content type are ``str`` or ``None``; the content is file
|
|
1221
|
+
content; the headers, the file part's own, a mapping of ``str`` to
|
|
1222
|
+
``str``. A bare ``tuple`` has no item types, so it counts as ``Any``.
|
|
1223
|
+
"""
|
|
1224
|
+
type_args = get_args(annotation)
|
|
1225
|
+
if not type_args:
|
|
1226
|
+
return True
|
|
1227
|
+
if len(type_args) not in {2, 3, 4} or Ellipsis in type_args:
|
|
1228
|
+
return False
|
|
1229
|
+
filename, content, *rest = type_args
|
|
1230
|
+
content_arms = _arms(content)
|
|
1231
|
+
return (
|
|
1232
|
+
_is_text_or_none(filename)
|
|
1233
|
+
and bool(content_arms)
|
|
1234
|
+
and all(_is_file_content(arm) for arm in content_arms)
|
|
1235
|
+
and all(_is_text_or_none(item) for item in rest[:1])
|
|
1236
|
+
and all(_is_text_mapping(item) for item in rest[1:])
|
|
1237
|
+
)
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
def _is_text_mapping(annotation: Any) -> bool:
|
|
1241
|
+
"""Return whether the type is a mapping of ``str`` to ``str``, or ``Any``.
|
|
1242
|
+
|
|
1243
|
+
A bare ``Mapping`` or ``dict`` has no item types, so it counts as ``Any``.
|
|
1244
|
+
"""
|
|
1245
|
+
arms = _arms(annotation)
|
|
1246
|
+
for arm in arms:
|
|
1247
|
+
if arm is Any:
|
|
1248
|
+
continue
|
|
1249
|
+
cls = _class_of(arm)
|
|
1250
|
+
if cls is None or not issubclass(cls, Mapping):
|
|
1251
|
+
return False
|
|
1252
|
+
if not all(_is_text_or_none(item) for item in get_args(arm)):
|
|
1253
|
+
return False
|
|
1254
|
+
return bool(arms)
|
|
1255
|
+
|
|
1256
|
+
|
|
1257
|
+
def _is_text_or_none(annotation: Any) -> bool:
|
|
1258
|
+
"""Return whether the type is ``str``, ``None``, both, or ``Any``."""
|
|
1259
|
+
return all(arm is Any or (isinstance(arm, type) and issubclass(arm, str)) for arm in _arms(annotation))
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
def _is_content(annotation: Any) -> bool:
|
|
1263
|
+
"""Return whether a value of this type is a raw body httpx2 can send.
|
|
1264
|
+
|
|
1265
|
+
That's ``str`` (sent as UTF-8), ``bytes``, or an iterable or async
|
|
1266
|
+
iterable of bytes, which is streamed; or ``Any``. A model, mapping,
|
|
1267
|
+
``bytearray`` or ``memoryview`` is iterable too, but not of bytes.
|
|
1268
|
+
"""
|
|
1269
|
+
if annotation is Any or annotation is NO_VALUE:
|
|
1270
|
+
return True
|
|
1271
|
+
cls = _class_of(annotation)
|
|
1272
|
+
if cls is None:
|
|
1273
|
+
return False
|
|
1274
|
+
if issubclass(cls, str | bytes):
|
|
1275
|
+
return True
|
|
1276
|
+
if issubclass(cls, BaseModel | Mapping | bytearray | memoryview) or not issubclass(cls, Iterable | AsyncIterable):
|
|
1277
|
+
return False
|
|
1278
|
+
# The item type comes first: Iterator[bytes], Generator[bytes, None, None].
|
|
1279
|
+
# A bare Iterator has none, so its items count as Any.
|
|
1280
|
+
type_args = get_args(annotation)
|
|
1281
|
+
return not type_args or all(arm is Any or arm is bytes for arm in _arms(type_args[0]))
|