pyopenapi-gen 0.13.0__py3-none-any.whl → 0.14.1__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.
- pyopenapi_gen/cli.py +3 -3
- pyopenapi_gen/context/import_collector.py +10 -10
- pyopenapi_gen/context/render_context.py +13 -13
- pyopenapi_gen/core/auth/plugins.py +7 -7
- pyopenapi_gen/core/http_status_codes.py +218 -0
- pyopenapi_gen/core/http_transport.py +19 -19
- pyopenapi_gen/core/loader/operations/parser.py +2 -2
- pyopenapi_gen/core/loader/operations/request_body.py +3 -3
- pyopenapi_gen/core/loader/parameters/parser.py +3 -3
- pyopenapi_gen/core/loader/responses/parser.py +2 -2
- pyopenapi_gen/core/loader/schemas/extractor.py +4 -4
- pyopenapi_gen/core/pagination.py +3 -3
- pyopenapi_gen/core/parsing/common/ref_resolution/helpers/list_response.py +3 -3
- pyopenapi_gen/core/parsing/common/ref_resolution/helpers/missing_ref.py +2 -2
- pyopenapi_gen/core/parsing/common/ref_resolution/helpers/new_schema.py +3 -3
- pyopenapi_gen/core/parsing/common/ref_resolution/helpers/stripped_suffix.py +3 -3
- pyopenapi_gen/core/parsing/common/ref_resolution/resolve_schema_ref.py +2 -2
- pyopenapi_gen/core/parsing/common/type_parser.py +2 -3
- pyopenapi_gen/core/parsing/context.py +10 -10
- pyopenapi_gen/core/parsing/cycle_helpers.py +5 -2
- pyopenapi_gen/core/parsing/keywords/all_of_parser.py +5 -5
- pyopenapi_gen/core/parsing/keywords/any_of_parser.py +4 -4
- pyopenapi_gen/core/parsing/keywords/array_items_parser.py +4 -4
- pyopenapi_gen/core/parsing/keywords/one_of_parser.py +4 -4
- pyopenapi_gen/core/parsing/keywords/properties_parser.py +5 -5
- pyopenapi_gen/core/parsing/schema_finalizer.py +15 -15
- pyopenapi_gen/core/parsing/schema_parser.py +44 -25
- pyopenapi_gen/core/parsing/transformers/inline_enum_extractor.py +4 -4
- pyopenapi_gen/core/parsing/transformers/inline_object_promoter.py +7 -4
- pyopenapi_gen/core/parsing/unified_cycle_detection.py +10 -10
- pyopenapi_gen/core/postprocess_manager.py +85 -12
- pyopenapi_gen/core/schemas.py +10 -10
- pyopenapi_gen/core/streaming_helpers.py +5 -7
- pyopenapi_gen/core/telemetry.py +4 -4
- pyopenapi_gen/core/utils.py +7 -7
- pyopenapi_gen/core/writers/code_writer.py +2 -2
- pyopenapi_gen/core/writers/documentation_writer.py +18 -18
- pyopenapi_gen/core/writers/line_writer.py +3 -3
- pyopenapi_gen/core/writers/python_construct_renderer.py +15 -11
- pyopenapi_gen/emit/models_emitter.py +2 -2
- pyopenapi_gen/emitters/core_emitter.py +3 -5
- pyopenapi_gen/emitters/endpoints_emitter.py +12 -12
- pyopenapi_gen/emitters/exceptions_emitter.py +153 -18
- pyopenapi_gen/emitters/models_emitter.py +6 -6
- pyopenapi_gen/generator/client_generator.py +10 -8
- pyopenapi_gen/helpers/endpoint_utils.py +16 -18
- pyopenapi_gen/helpers/type_cleaner.py +66 -53
- pyopenapi_gen/helpers/type_helper.py +7 -7
- pyopenapi_gen/helpers/type_resolution/array_resolver.py +4 -4
- pyopenapi_gen/helpers/type_resolution/composition_resolver.py +5 -5
- pyopenapi_gen/helpers/type_resolution/finalizer.py +38 -22
- pyopenapi_gen/helpers/type_resolution/named_resolver.py +4 -5
- pyopenapi_gen/helpers/type_resolution/object_resolver.py +11 -11
- pyopenapi_gen/helpers/type_resolution/primitive_resolver.py +1 -2
- pyopenapi_gen/helpers/type_resolution/resolver.py +2 -3
- pyopenapi_gen/ir.py +32 -34
- pyopenapi_gen/types/contracts/protocols.py +5 -5
- pyopenapi_gen/types/contracts/types.py +2 -3
- pyopenapi_gen/types/resolvers/reference_resolver.py +4 -4
- pyopenapi_gen/types/resolvers/response_resolver.py +6 -4
- pyopenapi_gen/types/resolvers/schema_resolver.py +32 -16
- pyopenapi_gen/types/services/type_service.py +55 -9
- pyopenapi_gen/types/strategies/response_strategy.py +6 -7
- pyopenapi_gen/visit/client_visitor.py +5 -7
- pyopenapi_gen/visit/endpoint/generators/docstring_generator.py +7 -7
- pyopenapi_gen/visit/endpoint/generators/request_generator.py +5 -5
- pyopenapi_gen/visit/endpoint/generators/response_handler_generator.py +41 -19
- pyopenapi_gen/visit/endpoint/generators/signature_generator.py +4 -4
- pyopenapi_gen/visit/endpoint/generators/url_args_generator.py +17 -17
- pyopenapi_gen/visit/endpoint/processors/import_analyzer.py +8 -8
- pyopenapi_gen/visit/endpoint/processors/parameter_processor.py +13 -13
- pyopenapi_gen/visit/exception_visitor.py +54 -16
- pyopenapi_gen/visit/model/alias_generator.py +1 -4
- pyopenapi_gen/visit/model/dataclass_generator.py +139 -10
- pyopenapi_gen/visit/model/model_visitor.py +2 -3
- pyopenapi_gen/visit/visitor.py +3 -3
- {pyopenapi_gen-0.13.0.dist-info → pyopenapi_gen-0.14.1.dist-info}/METADATA +1 -1
- pyopenapi_gen-0.14.1.dist-info/RECORD +132 -0
- pyopenapi_gen-0.13.0.dist-info/RECORD +0 -131
- {pyopenapi_gen-0.13.0.dist-info → pyopenapi_gen-0.14.1.dist-info}/WHEEL +0 -0
- {pyopenapi_gen-0.13.0.dist-info → pyopenapi_gen-0.14.1.dist-info}/entry_points.txt +0 -0
- {pyopenapi_gen-0.13.0.dist-info → pyopenapi_gen-0.14.1.dist-info}/licenses/LICENSE +0 -0
@@ -5,8 +5,9 @@ Helper class for generating response handling logic for an endpoint method.
|
|
5
5
|
from __future__ import annotations
|
6
6
|
|
7
7
|
import logging
|
8
|
-
from typing import TYPE_CHECKING, Any,
|
8
|
+
from typing import TYPE_CHECKING, Any, TypedDict
|
9
9
|
|
10
|
+
from pyopenapi_gen.core.http_status_codes import get_exception_class_name
|
10
11
|
from pyopenapi_gen.core.writers.code_writer import CodeWriter
|
11
12
|
from pyopenapi_gen.helpers.endpoint_utils import (
|
12
13
|
_get_primary_response,
|
@@ -43,8 +44,8 @@ class DefaultCase(TypedDict):
|
|
43
44
|
class EndpointResponseHandlerGenerator:
|
44
45
|
"""Generates the response handling logic for an endpoint method."""
|
45
46
|
|
46
|
-
def __init__(self, schemas:
|
47
|
-
self.schemas:
|
47
|
+
def __init__(self, schemas: dict[str, Any] | None = None) -> None:
|
48
|
+
self.schemas: dict[str, Any] = schemas or {}
|
48
49
|
|
49
50
|
def _is_type_alias_to_array(self, type_name: str) -> bool:
|
50
51
|
"""
|
@@ -129,7 +130,7 @@ class EndpointResponseHandlerGenerator:
|
|
129
130
|
Determine if a type should use BaseSchema deserialization.
|
130
131
|
|
131
132
|
Args:
|
132
|
-
type_name: The Python type name (e.g., "User", "List[User]", "
|
133
|
+
type_name: The Python type name (e.g., "User", "List[User]", "User | None")
|
133
134
|
|
134
135
|
Returns:
|
135
136
|
True if the type should use BaseSchema .from_dict() deserialization
|
@@ -137,14 +138,14 @@ class EndpointResponseHandlerGenerator:
|
|
137
138
|
# Extract the base type name from complex types
|
138
139
|
base_type = type_name
|
139
140
|
|
140
|
-
# Handle List[Type],
|
141
|
+
# Handle List[Type], Type | None, etc.
|
141
142
|
if "[" in base_type and "]" in base_type:
|
142
|
-
# Extract the inner type from List[Type],
|
143
|
+
# Extract the inner type from List[Type], Type | None, etc.
|
143
144
|
start_bracket = base_type.find("[")
|
144
145
|
end_bracket = base_type.rfind("]")
|
145
146
|
inner_type = base_type[start_bracket + 1 : end_bracket]
|
146
147
|
|
147
|
-
# For Union types like
|
148
|
+
# For Union types like User | None -> Union[User, None], take the first type
|
148
149
|
if ", " in inner_type:
|
149
150
|
inner_type = inner_type.split(", ")[0]
|
150
151
|
|
@@ -167,8 +168,9 @@ class EndpointResponseHandlerGenerator:
|
|
167
168
|
}:
|
168
169
|
return False
|
169
170
|
|
170
|
-
# Skip typing constructs
|
171
|
-
|
171
|
+
# Skip typing constructs
|
172
|
+
# Note: Modern Python 3.10+ uses | None instead of Optional[X]
|
173
|
+
if base_type.startswith(("dict[", "List[", "Union[", "Tuple[", "dict[", "list[", "tuple[")):
|
172
174
|
return False
|
173
175
|
|
174
176
|
# Check if this is a type alias (array or non-array) - these should NOT use BaseSchema
|
@@ -179,8 +181,7 @@ class EndpointResponseHandlerGenerator:
|
|
179
181
|
# Check if it's a model type (contains a dot indicating it's from models package)
|
180
182
|
# or if it's a simple class name that's likely a generated model (starts with uppercase)
|
181
183
|
return "." in base_type or (
|
182
|
-
base_type[0].isupper()
|
183
|
-
and base_type not in {"Dict", "List", "Optional", "Union", "Tuple", "dict", "list", "tuple"}
|
184
|
+
base_type[0].isupper() and base_type not in {"Dict", "List", "Union", "Tuple", "dict", "list", "tuple"}
|
184
185
|
)
|
185
186
|
|
186
187
|
def _get_base_schema_deserialization_code(self, return_type: str, data_expr: str) -> str:
|
@@ -202,8 +203,29 @@ class EndpointResponseHandlerGenerator:
|
|
202
203
|
item_type = return_type[5:-1] # Remove 'list[' and ']'
|
203
204
|
return f"[{item_type}.from_dict(item) for item in {data_expr}]"
|
204
205
|
elif return_type.startswith("Optional["):
|
205
|
-
#
|
206
|
+
# SANITY CHECK: Unified type system should never produce Optional[X]
|
207
|
+
logger.error(
|
208
|
+
f"❌ ARCHITECTURE VIOLATION: Received legacy Optional[X] type in response handler: {return_type}. "
|
209
|
+
f"Unified type system must generate X | None directly."
|
210
|
+
)
|
211
|
+
# Defensive conversion (but this indicates a serious bug upstream)
|
206
212
|
inner_type = return_type[9:-1] # Remove 'Optional[' and ']'
|
213
|
+
logger.warning(f"⚠️ Converting to modern syntax internally for: {inner_type} | None")
|
214
|
+
|
215
|
+
# Check if inner type is also a list
|
216
|
+
if inner_type.startswith("List[") or inner_type.startswith("list["):
|
217
|
+
list_code = self._get_base_schema_deserialization_code(inner_type, data_expr)
|
218
|
+
return f"{list_code} if {data_expr} is not None else None"
|
219
|
+
else:
|
220
|
+
return f"{inner_type}.from_dict({data_expr}) if {data_expr} is not None else None"
|
221
|
+
elif " | None" in return_type or return_type.endswith("| None"):
|
222
|
+
# Handle Model | None types (modern Python 3.10+ syntax)
|
223
|
+
# Extract base type from "X | None" pattern
|
224
|
+
if " | None" in return_type:
|
225
|
+
inner_type = return_type.replace(" | None", "").strip()
|
226
|
+
else:
|
227
|
+
inner_type = return_type.replace("| None", "").strip()
|
228
|
+
|
207
229
|
# Check if inner type is also a list
|
208
230
|
if inner_type.startswith("List[") or inner_type.startswith("list["):
|
209
231
|
list_code = self._get_base_schema_deserialization_code(inner_type, data_expr)
|
@@ -229,7 +251,7 @@ class EndpointResponseHandlerGenerator:
|
|
229
251
|
return_type: str,
|
230
252
|
context: RenderContext,
|
231
253
|
op: IROperation,
|
232
|
-
response_ir:
|
254
|
+
response_ir: IRResponse | None = None,
|
233
255
|
) -> str:
|
234
256
|
"""Determines the code snippet to extract/transform the response body."""
|
235
257
|
# Handle None, StreamingResponse, Iterator, etc.
|
@@ -242,7 +264,7 @@ class EndpointResponseHandlerGenerator:
|
|
242
264
|
if return_type == "AsyncIterator[bytes]":
|
243
265
|
context.add_import(f"{context.core_package_name}.streaming_helpers", "iter_bytes")
|
244
266
|
return "iter_bytes(response)"
|
245
|
-
elif "
|
267
|
+
elif "dict[str, Any]" in return_type or "dict" in return_type.lower():
|
246
268
|
# For event streams that return Dict objects
|
247
269
|
context.add_import(f"{context.core_package_name}.streaming_helpers", "iter_sse_events_text")
|
248
270
|
return "sse_json_stream_marker" # Special marker handled by _write_parsed_return
|
@@ -259,7 +281,7 @@ class EndpointResponseHandlerGenerator:
|
|
259
281
|
return "iter_bytes(response)"
|
260
282
|
|
261
283
|
# Special case for "data: Any" unwrapping when the actual schema has no fields/properties
|
262
|
-
if return_type in {"
|
284
|
+
if return_type in {"dict[str, Any]", "dict[str, object]", "object", "Any"}:
|
263
285
|
context.add_import("typing", "Dict")
|
264
286
|
context.add_import("typing", "Any")
|
265
287
|
|
@@ -272,7 +294,7 @@ class EndpointResponseHandlerGenerator:
|
|
272
294
|
return "response.json() # Type is Any"
|
273
295
|
elif return_type == "None":
|
274
296
|
return "None" # This will be handled by generate_response_handling directly
|
275
|
-
else: # Includes schema-defined models, List[],
|
297
|
+
else: # Includes schema-defined models, List[], dict[], Optional[]
|
276
298
|
context.add_typing_imports_for_type(return_type) # Ensure model itself is imported
|
277
299
|
|
278
300
|
# Check if we should use BaseSchema deserialization instead of cast()
|
@@ -353,8 +375,8 @@ class EndpointResponseHandlerGenerator:
|
|
353
375
|
else:
|
354
376
|
writer.write_line("return None")
|
355
377
|
else:
|
356
|
-
# Error responses
|
357
|
-
error_class_name =
|
378
|
+
# Error responses - use human-readable exception names
|
379
|
+
error_class_name = get_exception_class_name(status_code_val)
|
358
380
|
context.add_import(f"{context.core_package_name}", error_class_name)
|
359
381
|
writer.write_line(f"raise {error_class_name}(response=response)")
|
360
382
|
|
@@ -433,7 +455,7 @@ class EndpointResponseHandlerGenerator:
|
|
433
455
|
context.add_import("typing", "cast")
|
434
456
|
writer.write_line(f"return cast({strategy.return_type}, response.json())")
|
435
457
|
|
436
|
-
def _get_response_schema(self, response_ir: IRResponse) ->
|
458
|
+
def _get_response_schema(self, response_ir: IRResponse) -> IRSchema | None:
|
437
459
|
"""Extract the schema from a response IR."""
|
438
460
|
if not response_ir.content:
|
439
461
|
return None
|
@@ -5,7 +5,7 @@ Helper class for generating the method signature for an endpoint.
|
|
5
5
|
from __future__ import annotations
|
6
6
|
|
7
7
|
import logging
|
8
|
-
from typing import TYPE_CHECKING, Any,
|
8
|
+
from typing import TYPE_CHECKING, Any, List
|
9
9
|
|
10
10
|
from pyopenapi_gen.core.utils import NameSanitizer
|
11
11
|
from pyopenapi_gen.core.writers.code_writer import CodeWriter
|
@@ -24,15 +24,15 @@ logger = logging.getLogger(__name__)
|
|
24
24
|
class EndpointMethodSignatureGenerator:
|
25
25
|
"""Generates the Python method signature for an endpoint operation."""
|
26
26
|
|
27
|
-
def __init__(self, schemas:
|
28
|
-
self.schemas:
|
27
|
+
def __init__(self, schemas: dict[str, Any] | None = None) -> None:
|
28
|
+
self.schemas: dict[str, Any] = schemas or {}
|
29
29
|
|
30
30
|
def generate_signature(
|
31
31
|
self,
|
32
32
|
writer: CodeWriter,
|
33
33
|
op: IROperation,
|
34
34
|
context: RenderContext,
|
35
|
-
ordered_params: List[
|
35
|
+
ordered_params: List[dict[str, Any]],
|
36
36
|
strategy: ResponseStrategy,
|
37
37
|
) -> None:
|
38
38
|
"""Writes the method signature to the provided CodeWriter."""
|
@@ -6,7 +6,7 @@ from __future__ import annotations
|
|
6
6
|
|
7
7
|
import logging
|
8
8
|
import re # For _build_url_with_path_vars
|
9
|
-
from typing import TYPE_CHECKING, Any,
|
9
|
+
from typing import TYPE_CHECKING, Any, List
|
10
10
|
|
11
11
|
from pyopenapi_gen.core.utils import NameSanitizer
|
12
12
|
from pyopenapi_gen.core.writers.code_writer import CodeWriter
|
@@ -21,8 +21,8 @@ logger = logging.getLogger(__name__)
|
|
21
21
|
class EndpointUrlArgsGenerator:
|
22
22
|
"""Generates URL, query, and header parameters for an endpoint method."""
|
23
23
|
|
24
|
-
def __init__(self, schemas:
|
25
|
-
self.schemas:
|
24
|
+
def __init__(self, schemas: dict[str, Any] | None = None) -> None:
|
25
|
+
self.schemas: dict[str, Any] = schemas or {}
|
26
26
|
|
27
27
|
def _build_url_with_path_vars(self, path: str) -> str:
|
28
28
|
"""Builds the f-string for URL construction, substituting path variables."""
|
@@ -34,7 +34,7 @@ class EndpointUrlArgsGenerator:
|
|
34
34
|
return f'f"{{self.base_url}}{formatted_path}"'
|
35
35
|
|
36
36
|
def _write_query_params(
|
37
|
-
self, writer: CodeWriter, op: IROperation, ordered_params: List[
|
37
|
+
self, writer: CodeWriter, op: IROperation, ordered_params: List[dict[str, Any]], context: RenderContext
|
38
38
|
) -> None:
|
39
39
|
"""Writes query parameter dictionary construction."""
|
40
40
|
# Logic from EndpointMethodGenerator._write_query_params
|
@@ -58,7 +58,7 @@ class EndpointUrlArgsGenerator:
|
|
58
58
|
)
|
59
59
|
|
60
60
|
def _write_header_params(
|
61
|
-
self, writer: CodeWriter, op: IROperation, ordered_params: List[
|
61
|
+
self, writer: CodeWriter, op: IROperation, ordered_params: List[dict[str, Any]], context: RenderContext
|
62
62
|
) -> None:
|
63
63
|
"""Writes header parameter dictionary construction."""
|
64
64
|
# Logic from EndpointMethodGenerator._write_header_params
|
@@ -89,9 +89,9 @@ class EndpointUrlArgsGenerator:
|
|
89
89
|
writer: CodeWriter,
|
90
90
|
op: IROperation,
|
91
91
|
context: RenderContext,
|
92
|
-
ordered_params: List[
|
93
|
-
primary_content_type:
|
94
|
-
resolved_body_type:
|
92
|
+
ordered_params: List[dict[str, Any]],
|
93
|
+
primary_content_type: str | None,
|
94
|
+
resolved_body_type: str | None,
|
95
95
|
) -> bool:
|
96
96
|
"""Writes URL, query, and header parameters. Returns True if header params were written."""
|
97
97
|
# Main logic from EndpointMethodGenerator._write_url_and_args
|
@@ -103,9 +103,9 @@ class EndpointUrlArgsGenerator:
|
|
103
103
|
# Check if any parameter in ordered_params is a query param, not just op.parameters
|
104
104
|
has_spec_query_params = any(p.get("param_in") == "query" for p in ordered_params)
|
105
105
|
if has_spec_query_params:
|
106
|
-
context.add_import("typing", "Any") # For
|
107
|
-
context.add_import("typing", "Dict") # For
|
108
|
-
writer.write_line("params:
|
106
|
+
context.add_import("typing", "Any") # For dict[str, Any]
|
107
|
+
context.add_import("typing", "Dict") # For dict[str, Any]
|
108
|
+
writer.write_line("params: dict[str, Any] = {")
|
109
109
|
# writer.indent() # Indentation should be handled by CodeWriter when writing lines
|
110
110
|
self._write_query_params(writer, op, ordered_params, context)
|
111
111
|
# writer.dedent()
|
@@ -115,9 +115,9 @@ class EndpointUrlArgsGenerator:
|
|
115
115
|
# Header Parameters
|
116
116
|
has_header_params = any(p.get("param_in") == "header" for p in ordered_params)
|
117
117
|
if has_header_params:
|
118
|
-
context.add_import("typing", "Any") # For
|
119
|
-
context.add_import("typing", "Dict") # For
|
120
|
-
writer.write_line("headers:
|
118
|
+
context.add_import("typing", "Any") # For dict[str, Any]
|
119
|
+
context.add_import("typing", "Dict") # For dict[str, Any]
|
120
|
+
writer.write_line("headers: dict[str, Any] = {")
|
121
121
|
# writer.indent()
|
122
122
|
self._write_header_params(writer, op, ordered_params, context)
|
123
123
|
# writer.dedent()
|
@@ -160,11 +160,11 @@ class EndpointUrlArgsGenerator:
|
|
160
160
|
context.add_import("typing", "IO") # For IO[Any]
|
161
161
|
context.add_import("typing", "Any")
|
162
162
|
writer.write_line(
|
163
|
-
"files_data:
|
163
|
+
"files_data: dict[str, IO[Any]] = DataclassSerializer.serialize(files) # type failed"
|
164
164
|
)
|
165
165
|
elif primary_content_type == "application/x-www-form-urlencoded":
|
166
166
|
# form_data is the expected parameter name from EndpointParameterProcessor
|
167
|
-
# resolved_body_type should be
|
167
|
+
# resolved_body_type should be dict[str, Any]
|
168
168
|
if resolved_body_type:
|
169
169
|
writer.write_line(
|
170
170
|
f"form_data_body: {resolved_body_type} = DataclassSerializer.serialize(form_data)"
|
@@ -173,7 +173,7 @@ class EndpointUrlArgsGenerator:
|
|
173
173
|
context.add_import("typing", "Dict")
|
174
174
|
context.add_import("typing", "Any")
|
175
175
|
writer.write_line(
|
176
|
-
"form_data_body:
|
176
|
+
"form_data_body: dict[str, Any] = DataclassSerializer.serialize(form_data) # Fallback type"
|
177
177
|
)
|
178
178
|
elif resolved_body_type == "bytes": # e.g. application/octet-stream
|
179
179
|
# bytes_content is the expected parameter name from EndpointParameterProcessor
|
@@ -5,7 +5,7 @@ Helper class for analyzing an IROperation and registering necessary imports.
|
|
5
5
|
from __future__ import annotations
|
6
6
|
|
7
7
|
import logging
|
8
|
-
from typing import TYPE_CHECKING, Any
|
8
|
+
from typing import TYPE_CHECKING, Any # IO for multipart type hint
|
9
9
|
|
10
10
|
# Necessary helpers for type analysis
|
11
11
|
from pyopenapi_gen.helpers.endpoint_utils import (
|
@@ -24,8 +24,8 @@ logger = logging.getLogger(__name__)
|
|
24
24
|
class EndpointImportAnalyzer:
|
25
25
|
"""Analyzes an IROperation to determine and register required imports."""
|
26
26
|
|
27
|
-
def __init__(self, schemas:
|
28
|
-
self.schemas:
|
27
|
+
def __init__(self, schemas: dict[str, Any] | None = None) -> None:
|
28
|
+
self.schemas: dict[str, Any] = schemas or {}
|
29
29
|
|
30
30
|
def analyze_and_register_imports(
|
31
31
|
self,
|
@@ -40,21 +40,21 @@ class EndpointImportAnalyzer:
|
|
40
40
|
|
41
41
|
if op.request_body:
|
42
42
|
content_types = op.request_body.content.keys()
|
43
|
-
body_param_type:
|
43
|
+
body_param_type: str | None = None
|
44
44
|
if "multipart/form-data" in content_types:
|
45
|
-
# Type for multipart is
|
45
|
+
# Type for multipart is dict[str, IO[Any]] which requires IO and Any
|
46
46
|
context.add_import("typing", "Dict")
|
47
47
|
context.add_import("typing", "IO")
|
48
48
|
context.add_import("typing", "Any")
|
49
|
-
# The actual type string "
|
49
|
+
# The actual type string "dict[str, IO[Any]]" will be handled by add_typing_imports_for_type if passed
|
50
50
|
# but ensuring components are imported is key.
|
51
|
-
body_param_type = "
|
51
|
+
body_param_type = "dict[str, IO[Any]]"
|
52
52
|
elif "application/json" in content_types:
|
53
53
|
body_param_type = get_request_body_type(op.request_body, context, self.schemas)
|
54
54
|
elif "application/x-www-form-urlencoded" in content_types:
|
55
55
|
context.add_import("typing", "Dict")
|
56
56
|
context.add_import("typing", "Any")
|
57
|
-
body_param_type = "
|
57
|
+
body_param_type = "dict[str, Any]"
|
58
58
|
elif content_types: # Fallback for other types like application/octet-stream
|
59
59
|
body_param_type = "bytes"
|
60
60
|
|
@@ -5,7 +5,7 @@ Helper class for processing parameters for an endpoint method.
|
|
5
5
|
from __future__ import annotations
|
6
6
|
|
7
7
|
import logging
|
8
|
-
from typing import TYPE_CHECKING, Any,
|
8
|
+
from typing import TYPE_CHECKING, Any, List, Tuple
|
9
9
|
|
10
10
|
from pyopenapi_gen.core.utils import NameSanitizer
|
11
11
|
from pyopenapi_gen.helpers.endpoint_utils import get_param_type, get_request_body_type
|
@@ -24,12 +24,12 @@ class EndpointParameterProcessor:
|
|
24
24
|
method parameters for the endpoint signature and further processing.
|
25
25
|
"""
|
26
26
|
|
27
|
-
def __init__(self, schemas:
|
28
|
-
self.schemas:
|
27
|
+
def __init__(self, schemas: dict[str, Any] | None = None) -> None:
|
28
|
+
self.schemas: dict[str, Any] = schemas or {}
|
29
29
|
|
30
30
|
def process_parameters(
|
31
31
|
self, op: IROperation, context: RenderContext
|
32
|
-
) -> Tuple[List[
|
32
|
+
) -> Tuple[List[dict[str, Any]], str | None, str | None]:
|
33
33
|
"""
|
34
34
|
Prepares and orders parameters for an endpoint method, including path,
|
35
35
|
query, header, and request body parameters.
|
@@ -40,8 +40,8 @@ class EndpointParameterProcessor:
|
|
40
40
|
- primary_content_type: The dominant content type for the request body.
|
41
41
|
- resolved_body_type: The Python type hint for the request body.
|
42
42
|
"""
|
43
|
-
ordered_params: List[
|
44
|
-
param_details_map:
|
43
|
+
ordered_params: List[dict[str, Any]] = []
|
44
|
+
param_details_map: dict[str, dict[str, Any]] = {}
|
45
45
|
|
46
46
|
for param in op.parameters:
|
47
47
|
param_name_sanitized = NameSanitizer.sanitize_method_name(param.name)
|
@@ -56,21 +56,21 @@ class EndpointParameterProcessor:
|
|
56
56
|
ordered_params.append(param_info)
|
57
57
|
param_details_map[param_name_sanitized] = param_info
|
58
58
|
|
59
|
-
primary_content_type:
|
60
|
-
resolved_body_type:
|
59
|
+
primary_content_type: str | None = None
|
60
|
+
resolved_body_type: str | None = None
|
61
61
|
|
62
62
|
if op.request_body:
|
63
63
|
content_types = op.request_body.content.keys()
|
64
64
|
body_param_name = "body" # Default name
|
65
65
|
context.add_import("typing", "Any") # General fallback
|
66
|
-
body_specific_param_info:
|
66
|
+
body_specific_param_info: dict[str, Any] | None = None
|
67
67
|
|
68
68
|
if "multipart/form-data" in content_types:
|
69
69
|
primary_content_type = "multipart/form-data"
|
70
70
|
body_param_name = "files"
|
71
71
|
context.add_import("typing", "Dict")
|
72
72
|
context.add_import("typing", "IO")
|
73
|
-
resolved_body_type = "
|
73
|
+
resolved_body_type = "dict[str, IO[Any]]"
|
74
74
|
body_specific_param_info = {
|
75
75
|
"name": body_param_name,
|
76
76
|
"type": resolved_body_type,
|
@@ -95,7 +95,7 @@ class EndpointParameterProcessor:
|
|
95
95
|
primary_content_type = "application/x-www-form-urlencoded"
|
96
96
|
body_param_name = "form_data"
|
97
97
|
context.add_import("typing", "Dict")
|
98
|
-
resolved_body_type = "
|
98
|
+
resolved_body_type = "dict[str, Any]"
|
99
99
|
body_specific_param_info = {
|
100
100
|
"name": body_param_name,
|
101
101
|
"type": resolved_body_type,
|
@@ -138,8 +138,8 @@ class EndpointParameterProcessor:
|
|
138
138
|
return final_ordered_params, primary_content_type, resolved_body_type
|
139
139
|
|
140
140
|
def _ensure_path_variables_as_params(
|
141
|
-
self, op: IROperation, current_params: List[
|
142
|
-
) -> List[
|
141
|
+
self, op: IROperation, current_params: List[dict[str, Any]], param_details_map: dict[str, dict[str, Any]]
|
142
|
+
) -> List[dict[str, Any]]:
|
143
143
|
"""
|
144
144
|
Ensures that all variables in the URL path are present in the list of parameters.
|
145
145
|
If a path variable is not already defined as a parameter, it's added as a required string type.
|
@@ -1,40 +1,78 @@
|
|
1
1
|
from pyopenapi_gen import IRSpec
|
2
2
|
|
3
3
|
from ..context.render_context import RenderContext
|
4
|
+
from ..core.http_status_codes import (
|
5
|
+
get_exception_class_name,
|
6
|
+
get_status_name,
|
7
|
+
is_client_error,
|
8
|
+
is_error_code,
|
9
|
+
is_server_error,
|
10
|
+
)
|
4
11
|
from ..core.writers.python_construct_renderer import PythonConstructRenderer
|
5
12
|
|
6
13
|
|
7
14
|
class ExceptionVisitor:
|
8
|
-
"""Visitor for rendering exception alias classes from IRSpec.
|
15
|
+
"""Visitor for rendering exception alias classes from IRSpec.
|
16
|
+
|
17
|
+
This visitor generates exception classes only for error status codes (4xx and 5xx).
|
18
|
+
Success codes (2xx) are intentionally excluded as they represent successful responses.
|
19
|
+
"""
|
9
20
|
|
10
21
|
def __init__(self) -> None:
|
11
22
|
self.renderer = PythonConstructRenderer()
|
12
23
|
|
13
|
-
def visit(self, spec: IRSpec, context: RenderContext) -> tuple[str, list[str]]:
|
14
|
-
|
15
|
-
|
24
|
+
def visit(self, spec: IRSpec, context: RenderContext) -> tuple[str, list[str], list[int]]:
|
25
|
+
"""Generate exception classes from IRSpec.
|
26
|
+
|
27
|
+
Args:
|
28
|
+
spec: The IRSpec containing operations and responses
|
29
|
+
context: Render context for imports and code generation
|
30
|
+
|
31
|
+
Returns:
|
32
|
+
Tuple of (generated_code, exception_class_names, status_codes_list)
|
33
|
+
"""
|
34
|
+
# Register base exception imports (only the ones we actually use)
|
35
|
+
# Note: HTTPError is not used in exception_aliases.py, so we don't import it
|
36
|
+
context.add_import("httpx", "Response") # Third-party import first (Ruff I001)
|
16
37
|
context.add_import(f"{context.core_package_name}.exceptions", "ClientError")
|
17
38
|
context.add_import(f"{context.core_package_name}.exceptions", "ServerError")
|
18
|
-
context.add_import("httpx", "Response")
|
19
39
|
|
20
|
-
# Collect unique numeric status codes
|
21
|
-
|
22
|
-
|
23
|
-
|
40
|
+
# Collect unique numeric error status codes (4xx and 5xx only)
|
41
|
+
all_codes = {
|
42
|
+
int(resp.status_code) for op in spec.operations for resp in op.responses if resp.status_code.isdigit()
|
43
|
+
}
|
44
|
+
error_codes = sorted([code for code in all_codes if is_error_code(code)])
|
24
45
|
|
25
46
|
all_exception_code = []
|
26
47
|
generated_alias_names = []
|
27
48
|
|
28
49
|
# Use renderer to generate each exception class
|
29
|
-
for code in
|
30
|
-
|
31
|
-
|
50
|
+
for code in error_codes:
|
51
|
+
# Determine base class using helper functions
|
52
|
+
if is_client_error(code):
|
53
|
+
base_class = "ClientError"
|
54
|
+
elif is_server_error(code):
|
55
|
+
base_class = "ServerError"
|
56
|
+
else:
|
57
|
+
# Should not happen since we filtered to 4xx/5xx, but be defensive
|
58
|
+
continue
|
59
|
+
|
60
|
+
# Get human-readable exception class name (e.g., NotFoundError instead of Error404)
|
61
|
+
class_name = get_exception_class_name(code)
|
32
62
|
generated_alias_names.append(class_name)
|
33
|
-
|
63
|
+
|
64
|
+
# Get human-readable status name for documentation
|
65
|
+
status_name = get_status_name(code)
|
66
|
+
docstring = f"HTTP {code} {status_name}.\n\nRaised when the server responds with a {code} status code."
|
34
67
|
|
35
68
|
# Define the __init__ method body
|
36
69
|
init_method_body = [
|
37
70
|
"def __init__(self, response: Response) -> None:",
|
71
|
+
f' """Initialise {class_name} with the HTTP response.',
|
72
|
+
"", # Empty line without trailing whitespace (Ruff W293)
|
73
|
+
" Args:",
|
74
|
+
" response: The httpx Response object that triggered this exception",
|
75
|
+
' """',
|
38
76
|
" super().__init__(status_code=response.status_code, message=response.text, response=response)",
|
39
77
|
]
|
40
78
|
|
@@ -47,6 +85,6 @@ class ExceptionVisitor:
|
|
47
85
|
)
|
48
86
|
all_exception_code.append(exception_code)
|
49
87
|
|
50
|
-
# Join the generated class strings
|
51
|
-
final_code = "\n".join(all_exception_code)
|
52
|
-
return final_code, generated_alias_names
|
88
|
+
# Join the generated class strings with 2 blank lines between classes (PEP 8 / Ruff E302)
|
89
|
+
final_code = "\n\n\n".join(all_exception_code)
|
90
|
+
return final_code, generated_alias_names, error_codes
|
@@ -3,13 +3,11 @@ Generates Python code for type aliases from IRSchema objects.
|
|
3
3
|
"""
|
4
4
|
|
5
5
|
import logging
|
6
|
-
from typing import Dict, Optional
|
7
6
|
|
8
7
|
from pyopenapi_gen import IRSchema
|
9
8
|
from pyopenapi_gen.context.render_context import RenderContext
|
10
9
|
from pyopenapi_gen.core.utils import NameSanitizer
|
11
10
|
from pyopenapi_gen.core.writers.python_construct_renderer import PythonConstructRenderer
|
12
|
-
from pyopenapi_gen.helpers.type_resolution.finalizer import TypeFinalizer
|
13
11
|
from pyopenapi_gen.types.services.type_service import UnifiedTypeService
|
14
12
|
|
15
13
|
logger = logging.getLogger(__name__)
|
@@ -21,7 +19,7 @@ class AliasGenerator:
|
|
21
19
|
def __init__(
|
22
20
|
self,
|
23
21
|
renderer: PythonConstructRenderer,
|
24
|
-
all_schemas:
|
22
|
+
all_schemas: dict[str, IRSchema] | None,
|
25
23
|
):
|
26
24
|
# Pre-condition
|
27
25
|
if renderer is None:
|
@@ -70,7 +68,6 @@ class AliasGenerator:
|
|
70
68
|
|
71
69
|
alias_name = NameSanitizer.sanitize_class_name(base_name)
|
72
70
|
target_type = self.type_service.resolve_schema_type(schema, context, required=True, resolve_underlying=True)
|
73
|
-
target_type = TypeFinalizer(context)._clean_type(target_type)
|
74
71
|
|
75
72
|
# logger.debug(f"AliasGenerator: Rendering alias '{alias_name}' for target type '{target_type}'.")
|
76
73
|
|