Skip to content

Commit c68ef34

Browse files
committed
Update service_generator.py
1 parent 661b0ce commit c68ef34

File tree

1 file changed

+102
-31
lines changed

1 file changed

+102
-31
lines changed

src/openapi_python_generator/language_converters/python/service_generator.py

Lines changed: 102 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,9 @@ def generate_body_param(operation: Operation) -> Union[str, None]:
124124
if operation.requestBody is None:
125125
return None
126126
else:
127-
if isinstance(operation.requestBody, Reference30) or isinstance(operation.requestBody, Reference31):
127+
if isinstance(operation.requestBody, Reference30) or isinstance(
128+
operation.requestBody, Reference31
129+
):
128130
return "data.dict()"
129131

130132
if operation.requestBody.content is None:
@@ -138,7 +140,9 @@ def generate_body_param(operation: Operation) -> Union[str, None]:
138140
if media_type is None:
139141
return None # pragma: no cover
140142

141-
if isinstance(media_type.media_type_schema, (Reference, Reference30, Reference31)):
143+
if isinstance(
144+
media_type.media_type_schema, (Reference, Reference30, Reference31)
145+
):
142146
return "data.dict()"
143147
elif hasattr(media_type.media_type_schema, "ref"):
144148
# Handle Reference objects from different OpenAPI versions
@@ -150,7 +154,9 @@ def generate_body_param(operation: Operation) -> Union[str, None]:
150154
elif schema.type == "object":
151155
return "data"
152156
else:
153-
raise Exception(f"Unsupported schema type for request body: {schema.type}") # pragma: no cover
157+
raise Exception(
158+
f"Unsupported schema type for request body: {schema.type}"
159+
) # pragma: no cover
154160
else:
155161
raise Exception(
156162
f"Unsupported schema type for request body: {type(media_type.media_type_schema)}"
@@ -183,17 +189,26 @@ def _generate_params_from_content(content: Any):
183189
required = False
184190
param_name_cleaned = common.normalize_symbol(param.name)
185191

186-
if isinstance(param.param_schema, Schema30) or isinstance(param.param_schema, Schema31):
192+
if isinstance(param.param_schema, Schema30) or isinstance(
193+
param.param_schema, Schema31
194+
):
187195
converted_result = (
188196
f"{param_name_cleaned} : {type_converter(param.param_schema, param.required).converted_type}"
189197
+ ("" if param.required else " = None")
190198
)
191199
required = param.required
192-
elif isinstance(param.param_schema, Reference30) or isinstance(param.param_schema, Reference31):
193-
converted_result = f"{param_name_cleaned} : {param.param_schema.ref.split('/')[-1]}" + (
194-
""
195-
if isinstance(param, Reference30) or isinstance(param, Reference31) or param.required
196-
else " = None"
200+
elif isinstance(param.param_schema, Reference30) or isinstance(
201+
param.param_schema, Reference31
202+
):
203+
converted_result = (
204+
f"{param_name_cleaned} : {param.param_schema.ref.split('/')[-1]}"
205+
+ (
206+
""
207+
if isinstance(param, Reference30)
208+
or isinstance(param, Reference31)
209+
or param.required
210+
else " = None"
211+
)
197212
)
198213
required = isinstance(param, Reference) or param.required
199214

@@ -209,11 +224,17 @@ def _generate_params_from_content(content: Any):
209224
"application/octet-stream",
210225
]
211226

212-
if operation.requestBody is not None and not is_reference_type(operation.requestBody):
227+
if operation.requestBody is not None and not is_reference_type(
228+
operation.requestBody
229+
):
213230
# Safe access only if it's a concrete RequestBody object
214231
rb_content = getattr(operation.requestBody, "content", None)
215-
if isinstance(rb_content, dict) and any(rb_content.get(i) is not None for i in operation_request_body_types):
216-
get_keyword = [i for i in operation_request_body_types if rb_content.get(i)][0]
232+
if isinstance(rb_content, dict) and any(
233+
rb_content.get(i) is not None for i in operation_request_body_types
234+
):
235+
get_keyword = [
236+
i for i in operation_request_body_types if rb_content.get(i)
237+
][0]
217238
content = rb_content.get(get_keyword)
218239
if content is not None and hasattr(content, "media_type_schema"):
219240
mts = getattr(content, "media_type_schema", None)
@@ -223,7 +244,9 @@ def _generate_params_from_content(content: Any):
223244
):
224245
params += f"{_generate_params_from_content(mts)}, "
225246
else: # pragma: no cover
226-
raise Exception(f"Unsupported media type schema for {str(operation)}: {type(mts)}")
247+
raise Exception(
248+
f"Unsupported media type schema for {str(operation)}: {type(mts)}"
249+
)
227250
# else: silently ignore unsupported body shapes (could extend later)
228251
# Replace - with _ in params
229252
params = params.replace("-", "_")
@@ -232,7 +255,9 @@ def _generate_params_from_content(content: Any):
232255
return params + default_params
233256

234257

235-
def generate_operation_id(operation: Operation, http_op: str, path_name: Optional[str] = None) -> str:
258+
def generate_operation_id(
259+
operation: Operation, http_op: str, path_name: Optional[str] = None
260+
) -> str:
236261
if operation.operationId is not None:
237262
return common.normalize_symbol(operation.operationId)
238263
elif path_name is not None:
@@ -243,7 +268,9 @@ def generate_operation_id(operation: Operation, http_op: str, path_name: Optiona
243268
) # pragma: no cover
244269

245270

246-
def _generate_params(operation: Operation, param_in: Literal["query", "header"] = "query"):
271+
def _generate_params(
272+
operation: Operation, param_in: Literal["query", "header"] = "query"
273+
):
247274
if operation.parameters is None:
248275
return []
249276

@@ -290,7 +317,9 @@ def generate_return_type(operation: Operation) -> OpReturnType:
290317
media_type_schema = create_media_type_for_reference(chosen_response)
291318

292319
if media_type_schema is None:
293-
return OpReturnType(type=None, status_code=good_responses[0][0], complex_type=False)
320+
return OpReturnType(
321+
type=None, status_code=good_responses[0][0], complex_type=False
322+
)
294323

295324
if is_media_type(media_type_schema):
296325
inner_schema = getattr(media_type_schema, "media_type_schema", None)
@@ -307,18 +336,25 @@ def generate_return_type(operation: Operation) -> OpReturnType:
307336
)
308337
elif is_schema_type(inner_schema):
309338
converted_result = type_converter(inner_schema, True) # type: ignore
310-
if "array" in converted_result.original_type and isinstance(converted_result.import_types, list):
339+
if "array" in converted_result.original_type and isinstance(
340+
converted_result.import_types, list
341+
):
311342
matched = re.findall(r"List\[(.+)\]", converted_result.converted_type)
312343
if len(matched) > 0:
313344
list_type = matched[0]
314345
else: # pragma: no cover
315-
raise Exception(f"Unable to parse list type from {converted_result.converted_type}")
346+
raise Exception(
347+
f"Unable to parse list type from {converted_result.converted_type}"
348+
)
316349
else:
317350
list_type = None
318351
return OpReturnType(
319352
type=converted_result,
320353
status_code=good_responses[0][0],
321-
complex_type=bool(converted_result.import_types and len(converted_result.import_types) > 0),
354+
complex_type=bool(
355+
converted_result.import_types
356+
and len(converted_result.import_types) > 0
357+
),
322358
list_type=list_type,
323359
)
324360
else: # pragma: no cover
@@ -348,7 +384,11 @@ def generate_services(
348384
global _component_params
349385

350386
# Build a lookup dict for component parameters if available
351-
if components is not None and hasattr(components, "parameters") and components.parameters is not None:
387+
if (
388+
components is not None
389+
and hasattr(components, "parameters")
390+
and components.parameters is not None
391+
):
352392
_component_params = {}
353393
for param_name, param_or_ref in components.parameters.items():
354394
if isinstance(param_or_ref, (Parameter30, Parameter31)):
@@ -358,7 +398,9 @@ def generate_services(
358398

359399
jinja_env = create_jinja_env()
360400

361-
def generate_service_operation(op: Operation, path_name: str, async_type: bool) -> ServiceOperation:
401+
def generate_service_operation(
402+
op: Operation, path_name: str, async_type: bool
403+
) -> ServiceOperation:
362404
# Merge path-level parameters (always required by spec) into the
363405
# operation-level parameters so they get turned into function args.
364406
try:
@@ -372,25 +414,36 @@ def generate_service_operation(op: Operation, path_name: str, async_type: bool)
372414
if isinstance(p, (Parameter30, Parameter31)):
373415
existing_names.add(p.name)
374416
for p in path_level_params:
375-
if isinstance(p, (Parameter30, Parameter31)) and p.name not in existing_names:
417+
if (
418+
isinstance(p, (Parameter30, Parameter31))
419+
and p.name not in existing_names
420+
):
376421
if op.parameters is None:
377422
op.parameters = [] # type: ignore
378423
op.parameters.append(p) # type: ignore
379424
except Exception: # pragma: no cover
380-
print(f"Error merging path-level parameters for {path_name}") # pragma: no cover
425+
print(
426+
f"Error merging path-level parameters for {path_name}"
427+
) # pragma: no cover
381428
pass
382429

383430
params = generate_params(op)
384431
# Fallback: ensure all {placeholders} in path are present as function params
385432
try:
386-
placeholder_names = [m.group(1) for m in re.finditer(r"\{([^}/]+)\}", path_name)]
387-
existing_param_names = {p.split(":")[0].strip() for p in params.split(",") if ":" in p}
433+
placeholder_names = [
434+
m.group(1) for m in re.finditer(r"\{([^}/]+)\}", path_name)
435+
]
436+
existing_param_names = {
437+
p.split(":")[0].strip() for p in params.split(",") if ":" in p
438+
}
388439
for ph in placeholder_names:
389440
norm_ph = common.normalize_symbol(ph)
390441
if norm_ph not in existing_param_names and norm_ph:
391442
params = f"{norm_ph}: Any, " + params
392443
except Exception: # pragma: no cover
393-
print(f"Error ensuring path placeholders in params for {path_name}") # pragma: no cover
444+
print(
445+
f"Error ensuring path placeholders in params for {path_name}"
446+
) # pragma: no cover
394447
pass
395448
operation_id = generate_operation_id(op, http_operation, path_name)
396449
query_params = generate_query_params(op)
@@ -414,7 +467,9 @@ def generate_service_operation(op: Operation, path_name: str, async_type: bool)
414467
use_orjson=common.get_use_orjson(),
415468
)
416469

417-
so.content = jinja_env.get_template(library_config.template_name).render(**so.model_dump())
470+
so.content = jinja_env.get_template(library_config.template_name).render(
471+
**so.model_dump()
472+
)
418473

419474
if op.tags is not None and len(op.tags) > 0:
420475
so.tag = normalize_symbol(op.tags[0])
@@ -454,8 +509,16 @@ def generate_service_operation(op: Operation, path_name: str, async_type: bool)
454509
services.append(
455510
Service(
456511
file_name=f"{tag}_service",
457-
operations=[so for so in service_ops if so.tag == tag and not so.async_client],
458-
content="\n".join([so.content for so in service_ops if so.tag == tag and not so.async_client]),
512+
operations=[
513+
so for so in service_ops if so.tag == tag and not so.async_client
514+
],
515+
content="\n".join(
516+
[
517+
so.content
518+
for so in service_ops
519+
if so.tag == tag and not so.async_client
520+
]
521+
),
459522
async_client=False,
460523
library_import=library_config.library_name,
461524
use_orjson=common.get_use_orjson(),
@@ -466,8 +529,16 @@ def generate_service_operation(op: Operation, path_name: str, async_type: bool)
466529
services.append(
467530
Service(
468531
file_name=f"async_{tag}_service",
469-
operations=[so for so in service_ops if so.tag == tag and so.async_client],
470-
content="\n".join([so.content for so in service_ops if so.tag == tag and so.async_client]),
532+
operations=[
533+
so for so in service_ops if so.tag == tag and so.async_client
534+
],
535+
content="\n".join(
536+
[
537+
so.content
538+
for so in service_ops
539+
if so.tag == tag and so.async_client
540+
]
541+
),
471542
async_client=True,
472543
library_import=library_config.library_name,
473544
use_orjson=common.get_use_orjson(),

0 commit comments

Comments
 (0)