Skip to content

Commit 10bb98e

Browse files
committed
:fix: Adapted httpx to not use json.dumps for json field
1 parent 6366b19 commit 10bb98e

File tree

12 files changed

+132
-65
lines changed

12 files changed

+132
-65
lines changed

docs/tutorial/index.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -647,10 +647,10 @@ take a look at the `User.py` and the `Team.py` files:
647647

648648
``` py
649649
from typing import *
650-
650+
651651
from pydantic import BaseModel, Field
652-
653-
652+
653+
654654
class User(BaseModel):
655655
"""
656656
User model
@@ -675,9 +675,9 @@ take a look at the `User.py` and the `Team.py` files:
675675

676676
``` py
677677
from typing import *
678-
678+
679679
from pydantic import BaseModel, Field
680-
680+
681681
from .User import User
682682

683683

src/openapi_python_generator/language_converters/python/common.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import keyword
22
import re
33

4+
45
_use_orjson: bool = False
56
_symbol_ascii_strip_re = re.compile(r"[^A-Za-z0-9_]")
67

@@ -30,7 +31,7 @@ def normalize_symbol(symbol: str) -> str:
3031
:return: normalized identifier name
3132
"""
3233
symbol = symbol.replace("-", "_")
33-
normalized_symbol = _symbol_ascii_strip_re.sub('', symbol)
34+
normalized_symbol = _symbol_ascii_strip_re.sub("", symbol)
3435
if normalized_symbol in keyword.kwlist:
35-
normalized_symbol = normalized_symbol + '_'
36+
normalized_symbol = normalized_symbol + "_"
3637
return normalized_symbol

src/openapi_python_generator/language_converters/python/model_generator.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@
2121
from openapi_python_generator.models import TypeConversion
2222

2323

24-
def type_converter(schema: Schema, required: bool = False, model_name: Optional[str] = None,) -> TypeConversion:
24+
def type_converter(
25+
schema: Schema,
26+
required: bool = False,
27+
model_name: Optional[str] = None,
28+
) -> TypeConversion:
2529
"""
2630
Converts an OpenAPI type to a Python type.
2731
:param schema: Schema containing the type to be converted
@@ -119,7 +123,11 @@ def type_converter(schema: Schema, required: bool = False, model_name: Optional
119123
schema.schema_format is None or not common.get_use_orjson()
120124
):
121125
converted_type = pre_type + "str" + post_type
122-
elif schema.type == "string" and schema.schema_format.startswith("uuid") and common.get_use_orjson():
126+
elif (
127+
schema.type == "string"
128+
and schema.schema_format.startswith("uuid")
129+
and common.get_use_orjson()
130+
):
123131
if len(schema.schema_format) > 4 and schema.schema_format[4].isnumeric():
124132
uuid_type = schema.schema_format.upper()
125133
converted_type = pre_type + uuid_type + post_type
@@ -139,7 +147,9 @@ def type_converter(schema: Schema, required: bool = False, model_name: Optional
139147
elif schema.type == "array":
140148
retVal = pre_type + "List["
141149
if isinstance(schema.items, Reference):
142-
converted_reference = _generate_property_from_reference(model_name, "", schema.items, schema, required)
150+
converted_reference = _generate_property_from_reference(
151+
model_name, "", schema.items, schema, required
152+
)
143153
import_types = converted_reference.type.import_types
144154
original_type = "array<" + converted_reference.type.original_type + ">"
145155
retVal += converted_reference.type.converted_type
@@ -166,7 +176,7 @@ def type_converter(schema: Schema, required: bool = False, model_name: Optional
166176

167177

168178
def _generate_property_from_schema(
169-
model_name : str, name: str, schema: Schema, parent_schema: Optional[Schema] = None
179+
model_name: str, name: str, schema: Schema, parent_schema: Optional[Schema] = None
170180
) -> Property:
171181
"""
172182
Generates a property from a schema. It takes the type of the schema and converts it to a python type, and then
@@ -191,7 +201,11 @@ def _generate_property_from_schema(
191201

192202

193203
def _generate_property_from_reference(
194-
model_name: str, name: str, reference: Reference, parent_schema: Optional[Schema] = None, force_required: bool = False
204+
model_name: str,
205+
name: str,
206+
reference: Reference,
207+
parent_schema: Optional[Schema] = None,
208+
force_required: bool = False,
195209
) -> Property:
196210
"""
197211
Generates a property from a reference. It takes the name of the reference as the type, and then
@@ -212,13 +226,17 @@ def _generate_property_from_reference(
212226
if import_model == model_name:
213227
type_conv = TypeConversion(
214228
original_type=reference.ref,
215-
converted_type=import_model if required else 'Optional["' + import_model + '"]',
216-
import_types=None
229+
converted_type=import_model
230+
if required
231+
else 'Optional["' + import_model + '"]',
232+
import_types=None,
217233
)
218234
else:
219235
type_conv = TypeConversion(
220236
original_type=reference.ref,
221-
converted_type=import_model if required else "Optional[" + import_model + "]",
237+
converted_type=import_model
238+
if required
239+
else "Optional[" + import_model + "]",
222240
import_types=[f"from .{import_model} import {import_model}"],
223241
)
224242
return Property(

src/openapi_python_generator/language_converters/python/service_generator.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import re
2-
from typing import Dict, Literal
2+
from typing import Dict
33
from typing import List
4+
from typing import Literal
45
from typing import Tuple
56
from typing import Union
67

@@ -159,7 +160,9 @@ def generate_operation_id(operation: Operation, http_op: str) -> str:
159160
raise Exception(f"OperationId is not defined for {http_op}") # pragma: no cover
160161

161162

162-
def _generate_params(operation: Operation, param_in : Literal["query", "header"] = "query"):
163+
def _generate_params(
164+
operation: Operation, param_in: Literal["query", "header"] = "query"
165+
):
163166
if operation.parameters is None:
164167
return []
165168

@@ -171,12 +174,15 @@ def _generate_params(operation: Operation, param_in : Literal["query", "header"]
171174

172175
return params
173176

177+
174178
def generate_query_params(operation: Operation) -> List[str]:
175179
return _generate_params(operation, "query")
176180

181+
177182
def generate_header_params(operation: Operation) -> List[str]:
178183
return _generate_params(operation, "header")
179184

185+
180186
def generate_return_type(operation: Operation) -> OpReturnType:
181187
if operation.responses is None:
182188
return OpReturnType(type=None, status_code=200, complex_type=False)

src/openapi_python_generator/language_converters/python/templates/httpx.jinja2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ with httpx.Client(base_url=base_path, verify=api_config.verify) as client:
3232
{% if use_orjson %}
3333
content=orjson.dumps({{ body_param }})
3434
{% else %}
35-
json = json.dumps({{ body_param }})
35+
json = {{ body_param }}
3636
{% endif %}
3737
{% endif %}
3838
)

tests/regression/test_issue_11.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def runner() -> CliRunner:
1212
"""Fixture for invoking command-line interfaces."""
1313
return CliRunner()
1414

15+
1516
@pytest.mark.parametrize(
1617
"library",
1718
[HTTPLibrary.httpx, HTTPLibrary.requests, HTTPLibrary.aiohttp],
@@ -30,4 +31,3 @@ def test_issue_11(runner: CliRunner, model_data_with_cleanup, library) -> None:
3031
],
3132
)
3233
assert result.exit_code == 0
33-

tests/regression/test_issue_17.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def runner() -> CliRunner:
1313
"""Fixture for invoking command-line interfaces."""
1414
return CliRunner()
1515

16+
1617
@pytest.mark.parametrize(
1718
"library",
1819
[HTTPLibrary.httpx, HTTPLibrary.aiohttp, HTTPLibrary.requests],
@@ -21,7 +22,7 @@ def test_issue_11(runner: CliRunner, model_data_with_cleanup, library) -> None:
2122
"""
2223
https://github.com/MarcoMuellner/openapi-python-generator/issues/7
2324
"""
24-
assert generate_data(test_data_folder / "issue_17.json",
25-
test_result_path,
26-
library) is None
27-
25+
assert (
26+
generate_data(test_data_folder / "issue_17.json", test_result_path, library)
27+
is None
28+
)

tests/regression/test_issue_illegal_py_symbols.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ def runner() -> CliRunner:
1717
"library",
1818
[HTTPLibrary.httpx, HTTPLibrary.requests, HTTPLibrary.aiohttp],
1919
)
20-
def test_issue_keyword_parameter_name(runner: CliRunner, model_data_with_cleanup, library) -> None:
20+
def test_issue_keyword_parameter_name(
21+
runner: CliRunner, model_data_with_cleanup, library
22+
) -> None:
2123
result = runner.invoke(
2224
main,
2325
[
@@ -34,7 +36,9 @@ def test_issue_keyword_parameter_name(runner: CliRunner, model_data_with_cleanup
3436
"library",
3537
[HTTPLibrary.httpx, HTTPLibrary.requests, HTTPLibrary.aiohttp],
3638
)
37-
def test_issue_illegal_character_in_operation_id(runner: CliRunner, model_data_with_cleanup, library) -> None:
39+
def test_issue_illegal_character_in_operation_id(
40+
runner: CliRunner, model_data_with_cleanup, library
41+
) -> None:
3842
result = runner.invoke(
3943
main,
4044
[
@@ -44,4 +48,4 @@ def test_issue_illegal_character_in_operation_id(runner: CliRunner, model_data_w
4448
library.value,
4549
],
4650
)
47-
assert result.exit_code == 0
51+
assert result.exit_code == 0

tests/test_data/gitea_issue_11.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

tests/test_generated_code.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,10 +232,9 @@ def test_generate_code(model_data_with_cleanup, library, use_orjson, custom_ip):
232232

233233
passed_api_config = None
234234

235-
236-
237235
if custom_ip:
238236
from .test_result.api_config import APIConfig
237+
239238
passed_api_config = APIConfig()
240239
passed_api_config.base_path = custom_ip
241240

@@ -283,7 +282,16 @@ def test_generate_code(model_data_with_cleanup, library, use_orjson, custom_ip):
283282
_locals,
284283
)
285284
assert get_user_route.called
286-
assert len([(key,value) for key,value in get_user_route.calls[0][0].headers.raw if b'api-key' in key and b'test' in value]) == 1
285+
assert (
286+
len(
287+
[
288+
(key, value)
289+
for key, value in get_user_route.calls[0][0].headers.raw
290+
if b"api-key" in key and b"test" in value
291+
]
292+
)
293+
== 1
294+
)
287295

288296
data = dict(
289297
id=1, username="user1", email="[email protected]", password="123456", is_active=True

tests/test_model_generator.py

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,12 @@
9393
def test_type_converter_simple(test_openapi_types, expected_python_types):
9494
assert type_converter(test_openapi_types, True) == expected_python_types
9595

96-
if test_openapi_types.type == "array" and isinstance(test_openapi_types.items, Reference):
97-
expected_type = expected_python_types.converted_type.split("[")[-1].split("]")[0]
96+
if test_openapi_types.type == "array" and isinstance(
97+
test_openapi_types.items, Reference
98+
):
99+
expected_type = expected_python_types.converted_type.split("[")[-1].split("]")[
100+
0
101+
]
98102

99103
assert (
100104
type_converter(test_openapi_types, False).converted_type
@@ -160,48 +164,56 @@ def test_type_converter_simple(test_openapi_types, expected_python_types):
160164
),
161165
(
162166
Schema(type="string", schema_format="uuid"),
163-
TypeConversion(original_type="string", converted_type="UUID", import_types=['from uuid import UUID']),
167+
TypeConversion(
168+
original_type="string",
169+
converted_type="UUID",
170+
import_types=["from uuid import UUID"],
171+
),
164172
),
165173
(
166174
Schema(type="string", schema_format="uuid1"),
167175
TypeConversion(
168176
original_type="string",
169177
converted_type="UUID1",
170-
import_types=['from pydantic import UUID1']
178+
import_types=["from pydantic import UUID1"],
171179
),
172180
),
173181
(
174182
Schema(type="string", schema_format="uuid3"),
175183
TypeConversion(
176184
original_type="string",
177185
converted_type="UUID3",
178-
import_types=['from pydantic import UUID3']
186+
import_types=["from pydantic import UUID3"],
179187
),
180188
),
181189
(
182190
Schema(type="string", schema_format="uuid4"),
183191
TypeConversion(
184192
original_type="string",
185193
converted_type="UUID4",
186-
import_types=['from pydantic import UUID4']
194+
import_types=["from pydantic import UUID4"],
187195
),
188196
),
189197
(
190198
Schema(type="string", schema_format="uuid5"),
191199
TypeConversion(
192200
original_type="string",
193201
converted_type="UUID5",
194-
import_types=['from pydantic import UUID5']
202+
import_types=["from pydantic import UUID5"],
195203
),
196-
)
204+
),
197205
],
198206
)
199207
def test_type_converter_simple_orjson(test_openapi_types, expected_python_types):
200208
orjson_usage = common.get_use_orjson()
201209
common.set_use_orjson(True)
202210
assert type_converter(test_openapi_types, True) == expected_python_types
203-
if test_openapi_types.type == "array" and isinstance(test_openapi_types.items, Reference):
204-
expected_type = expected_python_types.converted_type.split("[")[-1].split("]")[0]
211+
if test_openapi_types.type == "array" and isinstance(
212+
test_openapi_types.items, Reference
213+
):
214+
expected_type = expected_python_types.converted_type.split("[")[-1].split("]")[
215+
0
216+
]
205217

206218
assert (
207219
type_converter(test_openapi_types, False).converted_type
@@ -318,8 +330,12 @@ def test_type_converter_exceptions():
318330
Schema(allOf=[Reference(ref="#/components/schemas/SomeModel")]),
319331
Schema(type="object", required=["SomeModel"]),
320332
Property(
321-
name='SomeModel',
322-
type=TypeConversion(original_type='tuple<#/components/schemas/SomeModel>', converted_type='"SomeModel"',import_types = []),
333+
name="SomeModel",
334+
type=TypeConversion(
335+
original_type="tuple<#/components/schemas/SomeModel>",
336+
converted_type='"SomeModel"',
337+
import_types=[],
338+
),
323339
required=True,
324340
imported_type=[],
325341
),
@@ -330,7 +346,9 @@ def test_type_converter_property(
330346
test_model_name, test_name, test_schema, test_parent_schema, expected_property
331347
):
332348
assert (
333-
_generate_property_from_schema(test_model_name,test_name, test_schema, test_parent_schema)
349+
_generate_property_from_schema(
350+
test_model_name, test_name, test_schema, test_parent_schema
351+
)
334352
== expected_property
335353
)
336354

@@ -376,7 +394,7 @@ def test_type_converter_property_reference(
376394
test_name, test_reference, parent_schema, expected_property
377395
):
378396
assert (
379-
_generate_property_from_reference("",test_name, test_reference, parent_schema)
397+
_generate_property_from_reference("", test_name, test_reference, parent_schema)
380398
== expected_property
381399
)
382400

0 commit comments

Comments
 (0)