From 926b83735ecc7adb6d46ae34376b8250e4f9b316 Mon Sep 17 00:00:00 2001 From: "valentin.kozlov" Date: Tue, 19 Sep 2023 17:16:30 +0200 Subject: [PATCH] [cli] Updated cli.py to account for "required" params and to updated returned structure --- deepaas/cmd/cli.py | 98 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 75 insertions(+), 23 deletions(-) diff --git a/deepaas/cmd/cli.py b/deepaas/cmd/cli.py index b13ca4dd..bb3cbadf 100644 --- a/deepaas/cmd/cli.py +++ b/deepaas/cmd/cli.py @@ -26,8 +26,10 @@ import shutil import sys import tempfile -import time +import uuid +from datetime import datetime +from marshmallow import fields from oslo_config import cfg from oslo_log import log @@ -38,6 +40,26 @@ debug_cli = False +# Not all types are covered! If not listed, the type is 'str' +# see https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html +FIELD_TYPE_CONVERTERS = { + fields.Bool: bool, + fields.Boolean: bool, + fields.Date: str, + fields.DateTime: str, + fields.Dict: dict, + fields.Email: str, + fields.Float: float, + fields.Int: int, + fields.Integer: int, + fields.List: list, + fields.Str: str, + fields.String: str, + fields.Time: str, + fields.URL: str, + fields.Url: str, + fields.UUID: str, +} # Helper function to get subdictionary from dict_one based on keys in dict_two def _get_subdict(dict_one, dict_two): @@ -55,35 +77,53 @@ def _fields_to_dict(fields_in): """Function to convert mashmallow fields to dict() :param fields_in: mashmallow fields :return: python dictionary - """ + """ dict_out = {} for key, val in fields_in.items(): - param = {} - param["default"] = val.missing - param["type"] = type(val.missing) - if key == "files" or key == "urls": - param["type"] = str + # initialise param with no 'default', type 'str' (!), empty 'help' + param = {'default': None, + 'type': str, + 'help': ''} + + # infer 'type' + # see FIELD_TYPE_CONVERTERS for converting + # mashmallow field types to python types + val_type = type(val) + if val_type in FIELD_TYPE_CONVERTERS: + param['type'] = FIELD_TYPE_CONVERTERS[val_type] + + if key == 'files' or key == 'urls': + param['type'] = str + + # infer 'required' + try: + val_req = val.required + except Exception: + val_req = False + param['required'] = val_req + + # infer 'default' + # if the field is not required, there must be default value + if not val_req: + param["default"] = val.missing - val_help = val.metadata["description"] + # infer 'help' + val_help = val.metadata['description'] # argparse hates % sign: - if "%" in val_help: + if '%' in val_help: # replace single occurancies of '%' with '%%' # since '%%' is accepted by argparse - val_help = re.sub(r"(?