|
23 | 23 | ExplicitNullValue, |
24 | 24 | OpenAPIOperation, |
25 | 25 | ) |
| 26 | +from .baked.util import get_path_segments |
26 | 27 | from .helpers import handle_url_overrides |
27 | 28 |
|
28 | 29 | if TYPE_CHECKING: |
@@ -347,30 +348,60 @@ def _build_request_body( |
347 | 348 |
|
348 | 349 | :return: A JSON string representing the request body, or None if not applicable. |
349 | 350 | """ |
350 | | - if operation.method == "get": |
351 | | - # Get operations don't have a body |
| 351 | + if operation.method in ("get", "delete"): |
| 352 | + # GET and DELETE operations don't have a body |
| 353 | + if ctx.raw_body is not None: |
| 354 | + print( |
| 355 | + f"--raw-body cannot be specified for actions with method {operation.method}", |
| 356 | + file=sys.stderr, |
| 357 | + ) |
| 358 | + sys.exit(ExitCodes.ARGUMENT_ERROR) |
| 359 | + |
352 | 360 | return None |
353 | 361 |
|
| 362 | + param_names = {param.name for param in operation.params} |
| 363 | + |
| 364 | + # Returns whether the given argument should be included in the request body |
| 365 | + def __should_include(key: str, value: Any) -> bool: |
| 366 | + return value is not None and key not in param_names |
| 367 | + |
| 368 | + # If the user has specified the --raw-body argument, |
| 369 | + # return it. |
| 370 | + if ctx.raw_body is not None: |
| 371 | + specified_keys = [ |
| 372 | + k for k, v in vars(parsed_args).items() if __should_include(k, v) |
| 373 | + ] |
| 374 | + |
| 375 | + if len(specified_keys) > 0: |
| 376 | + print( |
| 377 | + "--raw-body cannot be specified with action arguments: " |
| 378 | + + ", ".join(sorted(f"--{key}" for key in specified_keys)), |
| 379 | + file=sys.stderr, |
| 380 | + ) |
| 381 | + sys.exit(ExitCodes.ARGUMENT_ERROR) |
| 382 | + |
| 383 | + return ctx.raw_body |
| 384 | + |
354 | 385 | # Merge defaults into body if applicable |
355 | 386 | if ctx.defaults: |
356 | 387 | parsed_args = ctx.config.update(parsed_args, operation.allowed_defaults) |
357 | 388 |
|
358 | | - param_names = {param.name for param in operation.params} |
359 | | - |
360 | 389 | expanded_json = {} |
361 | 390 |
|
362 | 391 | # Expand dotted keys into nested dictionaries |
363 | 392 | for k, v in vars(parsed_args).items(): |
364 | | - if v is None or k in param_names: |
| 393 | + if not __should_include(k, v): |
365 | 394 | continue |
366 | 395 |
|
| 396 | + path_segments = get_path_segments(k) |
| 397 | + |
367 | 398 | cur = expanded_json |
368 | | - for part in k.split(".")[:-1]: |
| 399 | + for part in path_segments[:-1]: |
369 | 400 | if part not in cur: |
370 | 401 | cur[part] = {} |
371 | 402 | cur = cur[part] |
372 | 403 |
|
373 | | - cur[k.split(".")[-1]] = v |
| 404 | + cur[path_segments[-1]] = v |
374 | 405 |
|
375 | 406 | return json.dumps(_traverse_request_body(expanded_json)) |
376 | 407 |
|
|
0 commit comments