requestmodel 0.5.0__tar.gz → 0.6.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {requestmodel-0.5.0 → requestmodel-0.6.1}/PKG-INFO +4 -3
- {requestmodel-0.5.0 → requestmodel-0.6.1}/README.md +1 -1
- {requestmodel-0.5.0 → requestmodel-0.6.1}/pyproject.toml +5 -3
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/adapters/httpx.py +10 -6
- requestmodel-0.6.1/src/requestmodel/fastapi.py +324 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/model.py +32 -21
- requestmodel-0.6.1/src/requestmodel/params.py +37 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/utils.py +4 -18
- requestmodel-0.5.0/setup.py +0 -34
- requestmodel-0.5.0/src/requestmodel/encoders.py +0 -1
- requestmodel-0.5.0/src/requestmodel/params.py +0 -8
- {requestmodel-0.5.0 → requestmodel-0.6.1}/LICENSE +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/__init__.py +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/adapters/__init__.py +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/adapters/base.py +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/adapters/requests.py +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/py.typed +0 -0
- {requestmodel-0.5.0 → requestmodel-0.6.1}/src/requestmodel/typing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: requestmodel
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.1
|
|
4
4
|
Summary: requestmodel
|
|
5
5
|
Home-page: https://github.com/foarsitter/requestmodel
|
|
6
6
|
License: MIT
|
|
@@ -14,8 +14,9 @@ Classifier: Programming Language :: Python :: 3.8
|
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.9
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.10
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
-
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
18
|
Requires-Dist: httpx
|
|
19
|
+
Requires-Dist: pydantic (>=2.0.0,<3.0.0)
|
|
19
20
|
Project-URL: Changelog, https://github.com/foarsitter/requestmodel/releases
|
|
20
21
|
Project-URL: Documentation, https://requestmodel.readthedocs.io
|
|
21
22
|
Project-URL: Repository, https://github.com/foarsitter/requestmodel
|
|
@@ -46,7 +47,7 @@ Description-Content-Type: text/markdown
|
|
|
46
47
|
|
|
47
48
|
- Model your http requests as a pydantic model
|
|
48
49
|
- Annotate your request parameters with fastapi params
|
|
49
|
-
- Support
|
|
50
|
+
- Support for sync & async requests
|
|
50
51
|
|
|
51
52
|
## Goals
|
|
52
53
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "requestmodel"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.6.1"
|
|
4
4
|
description = "requestmodel"
|
|
5
5
|
authors = ["Jelmer Draaijer <info@jelmert.nl>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -17,15 +17,15 @@ Changelog = "https://github.com/foarsitter/requestmodel/releases"
|
|
|
17
17
|
|
|
18
18
|
[tool.poetry.dependencies]
|
|
19
19
|
python = ">=3.8"
|
|
20
|
-
fastapi = "*"
|
|
21
20
|
httpx = "*"
|
|
21
|
+
pydantic = "^2.0.0"
|
|
22
22
|
|
|
23
23
|
[tool.poetry.group.requests.dependencies]
|
|
24
24
|
requests = "^2.31.0"
|
|
25
25
|
|
|
26
26
|
[tool.poetry.group.dev.dependencies]
|
|
27
27
|
pytest-asyncio = "^0.21.1"
|
|
28
|
-
python-multipart = "^0.0.
|
|
28
|
+
python-multipart = "^0.0.7"
|
|
29
29
|
flask-wtf = "^1.2.1"
|
|
30
30
|
flask-pytest = "^0.0.5"
|
|
31
31
|
a2wsgi = "^1.8.0"
|
|
@@ -51,6 +51,7 @@ sphinx-autobuild = ">=2021.3.14"
|
|
|
51
51
|
typeguard = ">=2.13.3"
|
|
52
52
|
xdoctest = { extras = ["colors"], version = ">=0.15.10" }
|
|
53
53
|
myst-parser = { version = ">=0.16.1" }
|
|
54
|
+
fastapi = "^0.109.2"
|
|
54
55
|
|
|
55
56
|
[tool.coverage.paths]
|
|
56
57
|
source = ["src", "*/site-packages"]
|
|
@@ -59,6 +60,7 @@ tests = ["tests", "*/tests"]
|
|
|
59
60
|
[tool.coverage.run]
|
|
60
61
|
branch = true
|
|
61
62
|
source = ["requestmodel", "tests"]
|
|
63
|
+
omit = ["src/requestmodel/fastapi.py", '**/fastapi.py']
|
|
62
64
|
|
|
63
65
|
[tool.coverage.report]
|
|
64
66
|
show_missing = true
|
|
@@ -1,21 +1,25 @@
|
|
|
1
|
-
from typing import Any
|
|
2
|
-
|
|
3
1
|
from httpx import Request
|
|
4
2
|
from httpx._client import BaseClient
|
|
5
3
|
|
|
4
|
+
from requestmodel import params
|
|
6
5
|
from requestmodel.adapters.base import BaseAdapter
|
|
7
6
|
from requestmodel.model import RequestModel
|
|
8
|
-
|
|
9
|
-
from .. import params
|
|
7
|
+
from requestmodel.typing import ResponseType
|
|
10
8
|
|
|
11
9
|
|
|
12
10
|
class HTTPXAdapter(BaseAdapter):
|
|
13
11
|
name = "httpx"
|
|
14
12
|
|
|
15
|
-
def transform(
|
|
13
|
+
def transform(
|
|
14
|
+
self, client: BaseClient, model: RequestModel[ResponseType]
|
|
15
|
+
) -> Request:
|
|
16
16
|
request_args = model.request_args_for_values()
|
|
17
17
|
|
|
18
|
-
headers =
|
|
18
|
+
headers = client.headers
|
|
19
|
+
|
|
20
|
+
if request_args[params.Header]:
|
|
21
|
+
headers.update(request_args[params.Header])
|
|
22
|
+
|
|
19
23
|
body = request_args[params.Body]
|
|
20
24
|
|
|
21
25
|
is_json_request = "json" in headers.get("content-type", "")
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copied from fastapi.encoders
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import datetime
|
|
7
|
+
import re
|
|
8
|
+
import types
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from collections import deque
|
|
11
|
+
from dataclasses import is_dataclass
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from enum import Enum
|
|
14
|
+
from ipaddress import IPv4Address
|
|
15
|
+
from ipaddress import IPv4Interface
|
|
16
|
+
from ipaddress import IPv4Network
|
|
17
|
+
from ipaddress import IPv6Address
|
|
18
|
+
from ipaddress import IPv6Interface
|
|
19
|
+
from ipaddress import IPv6Network
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from pathlib import PurePath
|
|
22
|
+
from re import Pattern
|
|
23
|
+
from types import GeneratorType
|
|
24
|
+
from typing import Any
|
|
25
|
+
from typing import Callable
|
|
26
|
+
from typing import Deque
|
|
27
|
+
from typing import Dict
|
|
28
|
+
from typing import FrozenSet
|
|
29
|
+
from typing import List
|
|
30
|
+
from typing import Mapping
|
|
31
|
+
from typing import Optional
|
|
32
|
+
from typing import Sequence
|
|
33
|
+
from typing import Set
|
|
34
|
+
from typing import Tuple
|
|
35
|
+
from typing import Union
|
|
36
|
+
from uuid import UUID
|
|
37
|
+
|
|
38
|
+
from pydantic import BaseModel
|
|
39
|
+
from pydantic._internal._utils import lenient_issubclass
|
|
40
|
+
from pydantic.color import Color
|
|
41
|
+
from pydantic.networks import AnyUrl
|
|
42
|
+
from pydantic.networks import NameEmail
|
|
43
|
+
from pydantic.types import SecretBytes
|
|
44
|
+
from pydantic.types import SecretStr
|
|
45
|
+
from pydantic_core import Url as Url
|
|
46
|
+
from typing_extensions import get_args
|
|
47
|
+
from typing_extensions import get_origin
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Taken from Pydantic v1 as is
|
|
54
|
+
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
|
|
55
|
+
return o.isoformat()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# Taken from Pydantic v1 as is
|
|
59
|
+
# TODO: pv2 should this return strings instead?
|
|
60
|
+
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
|
|
61
|
+
"""
|
|
62
|
+
Encodes a Decimal as int of there's no exponent, otherwise float
|
|
63
|
+
|
|
64
|
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
|
65
|
+
where a integer (but not int typed) is used. Encoding this as a float
|
|
66
|
+
results in failed round-tripping between encode and parse.
|
|
67
|
+
Our Id type is a prime example of this.
|
|
68
|
+
|
|
69
|
+
>>> decimal_encoder(Decimal("1.0"))
|
|
70
|
+
1.0
|
|
71
|
+
|
|
72
|
+
>>> decimal_encoder(Decimal("1"))
|
|
73
|
+
1
|
|
74
|
+
"""
|
|
75
|
+
if dec_value.as_tuple().exponent >= 0: # type: ignore[operator]
|
|
76
|
+
return int(dec_value)
|
|
77
|
+
else:
|
|
78
|
+
return float(dec_value)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
ENCODERS_BY_TYPE: Dict[Any, Callable[[Any], Any]] = {
|
|
82
|
+
bytes: lambda o: o.decode(),
|
|
83
|
+
Color: str,
|
|
84
|
+
datetime.date: isoformat,
|
|
85
|
+
datetime.datetime: isoformat,
|
|
86
|
+
datetime.time: isoformat,
|
|
87
|
+
datetime.timedelta: lambda td: td.total_seconds(),
|
|
88
|
+
Decimal: decimal_encoder,
|
|
89
|
+
Enum: lambda o: o.value,
|
|
90
|
+
frozenset: list,
|
|
91
|
+
deque: list,
|
|
92
|
+
GeneratorType: list,
|
|
93
|
+
IPv4Address: str,
|
|
94
|
+
IPv4Interface: str,
|
|
95
|
+
IPv4Network: str,
|
|
96
|
+
IPv6Address: str,
|
|
97
|
+
IPv6Interface: str,
|
|
98
|
+
IPv6Network: str,
|
|
99
|
+
NameEmail: str,
|
|
100
|
+
Path: str,
|
|
101
|
+
Pattern: lambda o: o.pattern,
|
|
102
|
+
SecretBytes: str,
|
|
103
|
+
SecretStr: str,
|
|
104
|
+
set: list,
|
|
105
|
+
UUID: str,
|
|
106
|
+
Url: str,
|
|
107
|
+
AnyUrl: str,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def generate_encoders_by_class_tuples(
|
|
112
|
+
type_encoder_map: Dict[Any, Callable[[Any], Any]],
|
|
113
|
+
) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
|
|
114
|
+
encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(
|
|
115
|
+
tuple
|
|
116
|
+
)
|
|
117
|
+
for type_, encoder in type_encoder_map.items():
|
|
118
|
+
encoders_by_class_tuples[encoder] += (type_,)
|
|
119
|
+
return encoders_by_class_tuples
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def jsonable_encoder( # noqa: C901
|
|
126
|
+
obj: Any,
|
|
127
|
+
include: Optional[IncEx] = None,
|
|
128
|
+
exclude: Optional[IncEx] = None,
|
|
129
|
+
by_alias: bool = True,
|
|
130
|
+
exclude_unset: bool = False,
|
|
131
|
+
exclude_defaults: bool = False,
|
|
132
|
+
exclude_none: bool = False,
|
|
133
|
+
custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None,
|
|
134
|
+
sqlalchemy_safe: bool = True,
|
|
135
|
+
) -> Any:
|
|
136
|
+
"""
|
|
137
|
+
Convert any object to something that can be encoded in JSON.
|
|
138
|
+
|
|
139
|
+
This is used internally by FastAPI to make sure anything you return can be
|
|
140
|
+
encoded as JSON before it is sent to the client.
|
|
141
|
+
|
|
142
|
+
You can also use it yourself, for example to convert objects before saving them
|
|
143
|
+
in a database that supports only JSON.
|
|
144
|
+
|
|
145
|
+
Read more about it in the
|
|
146
|
+
[FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
|
|
147
|
+
""" # noqa: B950
|
|
148
|
+
|
|
149
|
+
if include is not None and not isinstance(include, (set, dict)):
|
|
150
|
+
include = set(include)
|
|
151
|
+
if exclude is not None and not isinstance(exclude, (set, dict)):
|
|
152
|
+
exclude = set(exclude)
|
|
153
|
+
if isinstance(obj, BaseModel):
|
|
154
|
+
obj_dict = obj.model_dump(
|
|
155
|
+
mode="json",
|
|
156
|
+
include=include,
|
|
157
|
+
exclude=exclude,
|
|
158
|
+
by_alias=by_alias,
|
|
159
|
+
exclude_unset=exclude_unset,
|
|
160
|
+
exclude_none=exclude_none,
|
|
161
|
+
exclude_defaults=exclude_defaults,
|
|
162
|
+
)
|
|
163
|
+
if "__root__" in obj_dict:
|
|
164
|
+
obj_dict = obj_dict["__root__"]
|
|
165
|
+
return jsonable_encoder(
|
|
166
|
+
obj_dict,
|
|
167
|
+
exclude_none=exclude_none,
|
|
168
|
+
exclude_defaults=exclude_defaults,
|
|
169
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
170
|
+
)
|
|
171
|
+
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
|
172
|
+
obj_dict = dataclasses.asdict(obj)
|
|
173
|
+
return jsonable_encoder(
|
|
174
|
+
obj_dict,
|
|
175
|
+
include=include,
|
|
176
|
+
exclude=exclude,
|
|
177
|
+
by_alias=by_alias,
|
|
178
|
+
exclude_unset=exclude_unset,
|
|
179
|
+
exclude_defaults=exclude_defaults,
|
|
180
|
+
exclude_none=exclude_none,
|
|
181
|
+
custom_encoder=custom_encoder,
|
|
182
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
183
|
+
)
|
|
184
|
+
if isinstance(obj, Enum):
|
|
185
|
+
return obj.value
|
|
186
|
+
if isinstance(obj, PurePath):
|
|
187
|
+
return str(obj)
|
|
188
|
+
if isinstance(obj, (str, int, float, type(None))):
|
|
189
|
+
return obj
|
|
190
|
+
if isinstance(obj, dict):
|
|
191
|
+
encoded_dict = {}
|
|
192
|
+
allowed_keys = set(obj.keys())
|
|
193
|
+
if include is not None:
|
|
194
|
+
allowed_keys &= set(include)
|
|
195
|
+
if exclude is not None:
|
|
196
|
+
allowed_keys -= set(exclude)
|
|
197
|
+
for key, value in obj.items():
|
|
198
|
+
if (
|
|
199
|
+
(
|
|
200
|
+
not sqlalchemy_safe
|
|
201
|
+
or (not isinstance(key, str))
|
|
202
|
+
or (not key.startswith("_sa"))
|
|
203
|
+
)
|
|
204
|
+
and (value is not None or not exclude_none)
|
|
205
|
+
and key in allowed_keys
|
|
206
|
+
):
|
|
207
|
+
encoded_key = jsonable_encoder(
|
|
208
|
+
key,
|
|
209
|
+
by_alias=by_alias,
|
|
210
|
+
exclude_unset=exclude_unset,
|
|
211
|
+
exclude_none=exclude_none,
|
|
212
|
+
custom_encoder=custom_encoder,
|
|
213
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
214
|
+
)
|
|
215
|
+
encoded_value = jsonable_encoder(
|
|
216
|
+
value,
|
|
217
|
+
by_alias=by_alias,
|
|
218
|
+
exclude_unset=exclude_unset,
|
|
219
|
+
exclude_none=exclude_none,
|
|
220
|
+
custom_encoder=custom_encoder,
|
|
221
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
222
|
+
)
|
|
223
|
+
encoded_dict[encoded_key] = encoded_value
|
|
224
|
+
return encoded_dict
|
|
225
|
+
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
|
|
226
|
+
encoded_list = []
|
|
227
|
+
for item in obj:
|
|
228
|
+
encoded_list.append(
|
|
229
|
+
jsonable_encoder(
|
|
230
|
+
item,
|
|
231
|
+
include=include,
|
|
232
|
+
exclude=exclude,
|
|
233
|
+
by_alias=by_alias,
|
|
234
|
+
exclude_unset=exclude_unset,
|
|
235
|
+
exclude_defaults=exclude_defaults,
|
|
236
|
+
exclude_none=exclude_none,
|
|
237
|
+
custom_encoder=custom_encoder,
|
|
238
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
return encoded_list
|
|
242
|
+
|
|
243
|
+
if type(obj) in ENCODERS_BY_TYPE:
|
|
244
|
+
return ENCODERS_BY_TYPE[type(obj)](obj)
|
|
245
|
+
for encoder, classes_tuple in encoders_by_class_tuples.items():
|
|
246
|
+
if isinstance(obj, classes_tuple):
|
|
247
|
+
return encoder(obj)
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
data = dict(obj)
|
|
251
|
+
except Exception as e:
|
|
252
|
+
errors: List[Exception] = [e]
|
|
253
|
+
try:
|
|
254
|
+
data = vars(obj)
|
|
255
|
+
except Exception as e:
|
|
256
|
+
errors.append(e)
|
|
257
|
+
raise ValueError(errors) from e
|
|
258
|
+
return jsonable_encoder(
|
|
259
|
+
data,
|
|
260
|
+
include=include,
|
|
261
|
+
exclude=exclude,
|
|
262
|
+
by_alias=by_alias,
|
|
263
|
+
exclude_unset=exclude_unset,
|
|
264
|
+
exclude_defaults=exclude_defaults,
|
|
265
|
+
exclude_none=exclude_none,
|
|
266
|
+
custom_encoder=custom_encoder,
|
|
267
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
UnionType = getattr(types, "UnionType", Union)
|
|
272
|
+
sequence_annotation_to_type = {
|
|
273
|
+
Sequence: list,
|
|
274
|
+
List: list,
|
|
275
|
+
list: list,
|
|
276
|
+
Tuple: tuple,
|
|
277
|
+
tuple: tuple,
|
|
278
|
+
Set: set,
|
|
279
|
+
set: set,
|
|
280
|
+
FrozenSet: frozenset,
|
|
281
|
+
frozenset: frozenset,
|
|
282
|
+
Deque: deque,
|
|
283
|
+
deque: deque,
|
|
284
|
+
}
|
|
285
|
+
sequence_types = tuple(sequence_annotation_to_type.keys())
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _annotation_is_sequence(annotation: Any) -> bool:
|
|
289
|
+
if lenient_issubclass(annotation, (str, bytes)):
|
|
290
|
+
return False
|
|
291
|
+
return lenient_issubclass(annotation, sequence_types)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _annotation_is_complex(annotation: Any) -> bool:
|
|
295
|
+
return (
|
|
296
|
+
lenient_issubclass(annotation, (BaseModel, Mapping))
|
|
297
|
+
or _annotation_is_sequence(annotation)
|
|
298
|
+
or is_dataclass(annotation)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def field_annotation_is_complex(
|
|
303
|
+
annotation: Any,
|
|
304
|
+
) -> bool:
|
|
305
|
+
origin = get_origin(annotation)
|
|
306
|
+
if origin is Union or origin is UnionType:
|
|
307
|
+
return any(field_annotation_is_complex(arg) for arg in get_args(annotation))
|
|
308
|
+
|
|
309
|
+
return (
|
|
310
|
+
_annotation_is_complex(annotation)
|
|
311
|
+
or _annotation_is_complex(origin)
|
|
312
|
+
or hasattr(origin, "__pydantic_core_schema__")
|
|
313
|
+
or hasattr(origin, "__get_pydantic_core_schema__")
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def field_annotation_is_sequence(annotation: Any) -> bool:
|
|
318
|
+
return _annotation_is_sequence(annotation) or _annotation_is_sequence(
|
|
319
|
+
get_origin(annotation)
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def get_path_param_names(path: str) -> Set[str]:
|
|
324
|
+
return set(re.findall("{(.*?)}", path))
|
|
@@ -16,10 +16,9 @@ from pydantic import TypeAdapter
|
|
|
16
16
|
from typing_extensions import get_type_hints
|
|
17
17
|
from typing_extensions import override
|
|
18
18
|
|
|
19
|
-
from
|
|
20
|
-
from
|
|
21
|
-
|
|
22
|
-
from .encoders import jsonable_encoder
|
|
19
|
+
from . import params
|
|
20
|
+
from .fastapi import get_path_param_names
|
|
21
|
+
from .fastapi import jsonable_encoder
|
|
23
22
|
from .typing import RequestArgs
|
|
24
23
|
from .typing import ResponseType
|
|
25
24
|
from .utils import flatten_body
|
|
@@ -37,7 +36,7 @@ class BaseRequestModel(BaseModel, Generic[ResponseType]):
|
|
|
37
36
|
response_model: ClassVar[Type[ResponseType]] # type: ignore[misc]
|
|
38
37
|
|
|
39
38
|
def get_path_param_names(self) -> Set[str]:
|
|
40
|
-
return
|
|
39
|
+
return get_path_param_names(self.url)
|
|
41
40
|
|
|
42
41
|
def request_args_for_values(self) -> RequestArgs:
|
|
43
42
|
request_args: RequestArgs = {
|
|
@@ -70,16 +69,18 @@ class BaseRequestModel(BaseModel, Generic[ResponseType]):
|
|
|
70
69
|
else:
|
|
71
70
|
continue
|
|
72
71
|
|
|
72
|
+
attr_name = annotated_property.alias or key
|
|
73
|
+
|
|
73
74
|
if (
|
|
74
75
|
isinstance(annotated_property, params.Header)
|
|
75
76
|
and annotated_property.convert_underscores
|
|
76
77
|
):
|
|
77
|
-
|
|
78
|
+
attr_name = attr_name.replace("_", "-")
|
|
78
79
|
|
|
79
80
|
if isinstance(annotated_property, params.Body):
|
|
80
|
-
unify_body(annotated_property,
|
|
81
|
+
unify_body(annotated_property, attr_name, request_args, value)
|
|
81
82
|
else:
|
|
82
|
-
request_args[type(annotated_property)][
|
|
83
|
+
request_args[type(annotated_property)][attr_name] = value
|
|
83
84
|
|
|
84
85
|
flatten_body(request_args)
|
|
85
86
|
|
|
@@ -87,7 +88,7 @@ class BaseRequestModel(BaseModel, Generic[ResponseType]):
|
|
|
87
88
|
|
|
88
89
|
|
|
89
90
|
class RequestModel(BaseRequestModel[ResponseType]):
|
|
90
|
-
|
|
91
|
+
raw_response: Optional[Response] = None
|
|
91
92
|
|
|
92
93
|
def handle_error(self, response: Response) -> None:
|
|
93
94
|
response.raise_for_status()
|
|
@@ -95,18 +96,20 @@ class RequestModel(BaseRequestModel[ResponseType]):
|
|
|
95
96
|
def send(self, client: Client) -> ResponseType:
|
|
96
97
|
"""Send the request synchronously"""
|
|
97
98
|
r = self.as_request(client)
|
|
98
|
-
self.
|
|
99
|
-
self.handle_error(self.
|
|
99
|
+
self.raw_response = client.send(r)
|
|
100
|
+
self.handle_error(self.raw_response)
|
|
100
101
|
if isinstance(self.response_model, TypeAdapter):
|
|
101
|
-
return self.response_model.validate_python(self.
|
|
102
|
-
return self.response_model.model_validate(self.
|
|
102
|
+
return self.response_model.validate_python(self.raw_response.json())
|
|
103
|
+
return self.response_model.model_validate(self.raw_response.json())
|
|
103
104
|
|
|
104
105
|
async def asend(self, client: AsyncClient) -> ResponseType:
|
|
105
106
|
"""Send the request asynchronously"""
|
|
106
107
|
r = self.as_request(client)
|
|
107
|
-
self.
|
|
108
|
-
self.handle_error(self.
|
|
109
|
-
|
|
108
|
+
self.raw_response = await client.send(r)
|
|
109
|
+
self.handle_error(self.raw_response)
|
|
110
|
+
if isinstance(self.response_model, TypeAdapter):
|
|
111
|
+
return self.response_model.validate_python(self.raw_response.json())
|
|
112
|
+
return self.response_model.model_validate(self.raw_response.json())
|
|
110
113
|
|
|
111
114
|
def as_request(self, client: BaseClient) -> Request:
|
|
112
115
|
"""Transform the properties of the object into a request"""
|
|
@@ -118,17 +121,25 @@ class RequestModel(BaseRequestModel[ResponseType]):
|
|
|
118
121
|
|
|
119
122
|
|
|
120
123
|
class IteratorRequestModel(RequestModel[ResponseType]):
|
|
121
|
-
|
|
124
|
+
raw_response: Optional[Response] = None
|
|
122
125
|
|
|
123
|
-
def
|
|
126
|
+
def next_from_response(self, response: ResponseType) -> bool: # pragma: no cover
|
|
127
|
+
"""
|
|
128
|
+
Prepare the current object for the next request and return true
|
|
129
|
+
|
|
130
|
+
In case of cursor pagination set the next token
|
|
131
|
+
In case of offset pagination increment the offset
|
|
132
|
+
|
|
133
|
+
"""
|
|
124
134
|
raise NotImplementedError
|
|
125
135
|
|
|
126
136
|
@override
|
|
127
137
|
def send(self, client: Client) -> Iterator[ResponseType]: # type: ignore[override]
|
|
128
138
|
response = super().send(client)
|
|
129
139
|
yield response
|
|
130
|
-
|
|
131
|
-
while self.
|
|
132
|
-
|
|
140
|
+
|
|
141
|
+
while self.next_from_response(response):
|
|
142
|
+
# avoid serializing the response
|
|
143
|
+
self.raw_response = None
|
|
133
144
|
response = super().send(client)
|
|
134
145
|
yield response
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from pydantic.fields import FieldInfo
|
|
2
|
+
from pydantic.fields import _FieldInfoInputs
|
|
3
|
+
from typing_extensions import Unpack
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Param(FieldInfo):
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Body(Param):
|
|
11
|
+
def __init__(self, embed: bool = False, **kwargs: Unpack[_FieldInfoInputs]) -> None:
|
|
12
|
+
super().__init__(**kwargs)
|
|
13
|
+
self.embed = embed
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Cookie(Param):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class File(Param):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Header(Param):
|
|
25
|
+
def __init__(
|
|
26
|
+
self, convert_underscores: bool = True, **kwargs: Unpack[_FieldInfoInputs]
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(**kwargs)
|
|
29
|
+
self.convert_underscores = convert_underscores
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Path(Param):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Query(Param):
|
|
37
|
+
pass
|
|
@@ -2,30 +2,16 @@ from typing import Any
|
|
|
2
2
|
from typing import Dict
|
|
3
3
|
from typing import Optional
|
|
4
4
|
from typing import Set
|
|
5
|
-
from typing import Type
|
|
6
|
-
from typing import Union
|
|
7
5
|
|
|
8
|
-
from fastapi import _compat
|
|
9
|
-
from fastapi import utils
|
|
10
6
|
from pydantic.fields import FieldInfo
|
|
11
7
|
from typing_extensions import Annotated
|
|
12
8
|
from typing_extensions import get_args
|
|
13
9
|
from typing_extensions import get_origin
|
|
14
10
|
|
|
15
|
-
from
|
|
16
|
-
from
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:
|
|
20
|
-
return _compat.field_annotation_is_complex(annotation)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
|
|
24
|
-
return _compat.field_annotation_is_sequence(annotation)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def get_path_param_names(path: str) -> Set[str]:
|
|
28
|
-
return utils.get_path_param_names(path)
|
|
11
|
+
from . import params
|
|
12
|
+
from .fastapi import field_annotation_is_complex
|
|
13
|
+
from .fastapi import field_annotation_is_sequence
|
|
14
|
+
from .typing import RequestArgs
|
|
29
15
|
|
|
30
16
|
|
|
31
17
|
def get_annotated_type(
|
requestmodel-0.5.0/setup.py
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
from setuptools import setup
|
|
3
|
-
|
|
4
|
-
package_dir = \
|
|
5
|
-
{'': 'src'}
|
|
6
|
-
|
|
7
|
-
packages = \
|
|
8
|
-
['requestmodel', 'requestmodel.adapters']
|
|
9
|
-
|
|
10
|
-
package_data = \
|
|
11
|
-
{'': ['*']}
|
|
12
|
-
|
|
13
|
-
install_requires = \
|
|
14
|
-
['fastapi', 'httpx']
|
|
15
|
-
|
|
16
|
-
setup_kwargs = {
|
|
17
|
-
'name': 'requestmodel',
|
|
18
|
-
'version': '0.5.0',
|
|
19
|
-
'description': 'requestmodel',
|
|
20
|
-
'long_description': "# requestmodel\n\n[][pypi status]\n[][pypi status]\n[][pypi status]\n[][license]\n\n[][read the docs]\n[][tests]\n[][codecov]\n\n[][pre-commit]\n[][black]\n\n[pypi status]: https://pypi.org/project/requestmodel/\n[read the docs]: https://requestmodel.readthedocs.io/\n[tests]: https://github.com/foarsitter/requestmodel/actions?workflow=Tests\n[codecov]: https://app.codecov.io/gh/foarsitter/requestmodel\n[pre-commit]: https://github.com/pre-commit/pre-commit\n[black]: https://github.com/psf/black\n\n## Features\n\n- Model your http requests as a pydantic model\n- Annotate your request parameters with fastapi params\n- Support voor sync & async requests\n\n## Goals\n\n- Create a generator for an OpenAPI spec\n- Support all kinds of http requests\n\n## Installation\n\nYou can install _requestmodel_ via [pip] from [PyPI]:\n\n```console\n$ pip install requestmodel\n```\n\n## Usage\n\nPlease see the [implementation detail] for further instructions.\n\n## Contributing\n\nContributions are very welcome.\nTo learn more, see the [Contributor Guide].\n\n## License\n\nDistributed under the terms of the [MIT license][license],\n_requestmodel_ is free and open source software.\n\n## Issues\n\nIf you encounter any problems,\nplease [file an issue] along with a detailed description.\n\n## Credits\n\nThis project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.\n\n[@cjolowicz]: https://github.com/cjolowicz\n[pypi]: https://pypi.org/\n[hypermodern python cookiecutter]: https://github.com/cjolowicz/cookiecutter-hypermodern-python\n[file an issue]: https://github.com/foarsitter/requestmodel/issues\n[pip]: https://pip.pypa.io/\n\n<!-- github-only -->\n\n[license]: https://github.com/foarsitter/requestmodel/blob/main/LICENSE\n[contributor guide]: https://github.com/foarsitter/requestmodel/blob/main/CONTRIBUTING.md\n[implementation detail]: https://requestmodel.readthedocs.io/en/latest/usage.html\n",
|
|
21
|
-
'author': 'Jelmer Draaijer',
|
|
22
|
-
'author_email': 'info@jelmert.nl',
|
|
23
|
-
'maintainer': 'None',
|
|
24
|
-
'maintainer_email': 'None',
|
|
25
|
-
'url': 'https://github.com/foarsitter/requestmodel',
|
|
26
|
-
'package_dir': package_dir,
|
|
27
|
-
'packages': packages,
|
|
28
|
-
'package_data': package_data,
|
|
29
|
-
'install_requires': install_requires,
|
|
30
|
-
'python_requires': '>=3.8',
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
setup(**setup_kwargs)
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
from fastapi.encoders import jsonable_encoder as jsonable_encoder # noqa
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
"""In the future it may be possible to implement our own params,
|
|
2
|
-
but for now we use the ones from FastAPI"""
|
|
3
|
-
from fastapi.params import Body as Body # noqa
|
|
4
|
-
from fastapi.params import Cookie as Cookie # noqa
|
|
5
|
-
from fastapi.params import File as File # noqa
|
|
6
|
-
from fastapi.params import Header as Header # noqa
|
|
7
|
-
from fastapi.params import Path as Path # noqa
|
|
8
|
-
from fastapi.params import Query as Query # noqa
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|