Skip to content

Commit 282d47d

Browse files
committed
Update service_generator.py
1 parent bb7e19c commit 282d47d

File tree

1 file changed

+99
-30
lines changed

1 file changed

+99
-30
lines changed

src/openapi_python_generator/language_converters/python/service_generator.py

Lines changed: 99 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,9 @@ def generate_body_param(operation: Operation) -> Union[str, None]:
126126
if operation.requestBody is None:
127127
return None
128128
else:
129-
if isinstance(operation.requestBody, Reference30) or isinstance(operation.requestBody, Reference31):
129+
if isinstance(operation.requestBody, Reference30) or isinstance(
130+
operation.requestBody, Reference31
131+
):
130132
return "data.dict()"
131133

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

143-
if isinstance(media_type.media_type_schema, (Reference, Reference30, Reference31)):
145+
if isinstance(
146+
media_type.media_type_schema, (Reference, Reference30, Reference31)
147+
):
144148
return "data.dict()"
145149
elif hasattr(media_type.media_type_schema, "ref"):
146150
# Handle Reference objects from different OpenAPI versions
@@ -152,7 +156,9 @@ def generate_body_param(operation: Operation) -> Union[str, None]:
152156
elif schema.type == "object":
153157
return "data"
154158
else:
155-
raise Exception(f"Unsupported schema type for request body: {schema.type}") # pragma: no cover
159+
raise Exception(
160+
f"Unsupported schema type for request body: {schema.type}"
161+
) # pragma: no cover
156162
else:
157163
raise Exception(
158164
f"Unsupported schema type for request body: {type(media_type.media_type_schema)}"
@@ -184,17 +190,26 @@ def _generate_params_from_content(content: Any):
184190
required = False
185191
param_name_cleaned = common.normalize_symbol(param.name)
186192

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

@@ -210,11 +225,17 @@ def _generate_params_from_content(content: Any):
210225
"application/octet-stream",
211226
]
212227

213-
if operation.requestBody is not None and not is_reference_type(operation.requestBody):
228+
if operation.requestBody is not None and not is_reference_type(
229+
operation.requestBody
230+
):
214231
# Safe access only if it's a concrete RequestBody object
215232
rb_content = getattr(operation.requestBody, "content", None)
216-
if isinstance(rb_content, dict) and any(rb_content.get(i) is not None for i in operation_request_body_types):
217-
get_keyword = [i for i in operation_request_body_types if rb_content.get(i)][0]
233+
if isinstance(rb_content, dict) and any(
234+
rb_content.get(i) is not None for i in operation_request_body_types
235+
):
236+
get_keyword = [
237+
i for i in operation_request_body_types if rb_content.get(i)
238+
][0]
218239
content = rb_content.get(get_keyword)
219240
if content is not None and hasattr(content, "media_type_schema"):
220241
mts = getattr(content, "media_type_schema", None)
@@ -224,7 +245,9 @@ def _generate_params_from_content(content: Any):
224245
):
225246
params += f"{_generate_params_from_content(mts)}, "
226247
else: # pragma: no cover
227-
raise Exception(f"Unsupported media type schema for {str(operation)}: {type(mts)}")
248+
raise Exception(
249+
f"Unsupported media type schema for {str(operation)}: {type(mts)}"
250+
)
228251
# else: silently ignore unsupported body shapes (could extend later)
229252
# Replace - with _ in params
230253
params = params.replace("-", "_")
@@ -233,7 +256,9 @@ def _generate_params_from_content(content: Any):
233256
return params + default_params
234257

235258

236-
def generate_operation_id(operation: Operation, http_op: str, path_name: Optional[str] = None) -> str:
259+
def generate_operation_id(
260+
operation: Operation, http_op: str, path_name: Optional[str] = None
261+
) -> str:
237262
if operation.operationId is not None:
238263
return common.normalize_symbol(operation.operationId)
239264
elif path_name is not None:
@@ -244,7 +269,9 @@ def generate_operation_id(operation: Operation, http_op: str, path_name: Optiona
244269
) # pragma: no cover
245270

246271

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

@@ -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
@@ -353,25 +389,36 @@ def _generate_service_operation(
353389
if isinstance(p, (Parameter30, Parameter31)):
354390
existing_names.add(p.name)
355391
for p in path_level_params:
356-
if isinstance(p, (Parameter30, Parameter31)) and p.name not in existing_names:
392+
if (
393+
isinstance(p, (Parameter30, Parameter31))
394+
and p.name not in existing_names
395+
):
357396
if op.parameters is None:
358397
op.parameters = [] # type: ignore
359398
op.parameters.append(p) # type: ignore
360399
except Exception: # pragma: no cover
361-
print(f"Error merging path-level parameters for {path_name}") # pragma: no cover
400+
print(
401+
f"Error merging path-level parameters for {path_name}"
402+
) # pragma: no cover
362403
pass
363404

364405
params = generate_params(op)
365406
# Fallback: ensure all {placeholders} in path are present as function params
366407
try:
367-
placeholder_names = [m.group(1) for m in re.finditer(r"\{([^}/]+)\}", path_name)]
368-
existing_param_names = {p.split(":")[0].strip() for p in params.split(",") if ":" in p}
408+
placeholder_names = [
409+
m.group(1) for m in re.finditer(r"\{([^}/]+)\}", path_name)
410+
]
411+
existing_param_names = {
412+
p.split(":")[0].strip() for p in params.split(",") if ":" in p
413+
}
369414
for ph in placeholder_names:
370415
norm_ph = common.normalize_symbol(ph)
371416
if norm_ph not in existing_param_names and norm_ph:
372417
params = f"{norm_ph}: Any, " + params
373418
except Exception: # pragma: no cover
374-
print(f"Error ensuring path placeholders in params for {path_name}") # pragma: no cover
419+
print(
420+
f"Error ensuring path placeholders in params for {path_name}"
421+
) # pragma: no cover
375422
pass
376423
operation_id = generate_operation_id(op, http_operation, path_name)
377424
query_params = generate_query_params(op)
@@ -395,7 +442,9 @@ def _generate_service_operation(
395442
use_orjson=common.get_use_orjson(),
396443
)
397444

398-
so.content = jinja_env.get_template(library_config.template_name).render(**so.model_dump())
445+
so.content = jinja_env.get_template(library_config.template_name).render(
446+
**so.model_dump()
447+
)
399448

400449
if op.tags is not None and len(op.tags) > 0:
401450
so.tag = normalize_symbol(op.tags[0])
@@ -422,7 +471,11 @@ def generate_services(
422471
"""
423472
global _component_params
424473

425-
if components is not None and hasattr(components, "parameters") and components.parameters is not None:
474+
if (
475+
components is not None
476+
and hasattr(components, "parameters")
477+
and components.parameters is not None
478+
):
426479
_component_params = {}
427480
for param_name, param_or_ref in components.parameters.items():
428481
if isinstance(param_or_ref, (Parameter30, Parameter31)):
@@ -476,8 +529,16 @@ def generate_services(
476529
services.append(
477530
Service(
478531
file_name=f"{tag}_service",
479-
operations=[so for so in service_ops if so.tag == tag and not so.async_client],
480-
content="\n".join([so.content for so in service_ops if so.tag == tag and not so.async_client]),
532+
operations=[
533+
so for so in service_ops if so.tag == tag and not so.async_client
534+
],
535+
content="\n".join(
536+
[
537+
so.content
538+
for so in service_ops
539+
if so.tag == tag and not so.async_client
540+
]
541+
),
481542
async_client=False,
482543
library_import=library_config.library_name,
483544
use_orjson=common.get_use_orjson(),
@@ -488,8 +549,16 @@ def generate_services(
488549
services.append(
489550
Service(
490551
file_name=f"async_{tag}_service",
491-
operations=[so for so in service_ops if so.tag == tag and so.async_client],
492-
content="\n".join([so.content for so in service_ops if so.tag == tag and so.async_client]),
552+
operations=[
553+
so for so in service_ops if so.tag == tag and so.async_client
554+
],
555+
content="\n".join(
556+
[
557+
so.content
558+
for so in service_ops
559+
if so.tag == tag and so.async_client
560+
]
561+
),
493562
async_client=True,
494563
library_import=library_config.library_name,
495564
use_orjson=common.get_use_orjson(),

0 commit comments

Comments
 (0)