如何使用bravadocore针对swagger验证json并在python中设置默认值

2024-04-29 13:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个招摇过市的2.0模型。我现在想根据swagger模型验证一些json文件。这样做没有任何问题:

from bravado_core.spec import Spec
from bravado_core.validate import validate_object
...
dir_path = os.path.dirname(os.path.abspath(__file__))
spec_path = os.path.join(dir_path, "schema_3.yaml")
spec_dict = get_swagger_spec()
spec = Spec.from_dict(spec_dict, config=bravado_config)
...
ConfigObjDict = spec_dict['definitions']['Configuration']

...
def validate(configuration):
    validate_object(spec, ConfigObjDict, configuration)
...
with open('sample_3.json') as f:
    configuration = json.loads(f.read())
    validate(configuration)

我遇到的问题是,在swagger文件中,我定义了一些与定义或项相关联的默认值,如果json文件根本不包含该项,我想使用相对默认值,我该怎么办?在

我试图使用unmarshal或挖掘bravado核心模块(handle_null_value),但暂时没有运气。在

最后,我尝试循环到json对象及其相关定义,例如:

^{pr2}$

但我被困住了,因为我不知道该怎么做。。。(当然应该是这样的递归解)

如有任何帮助或建议,我们将不胜感激

非常感谢。在


Tags: 文件pathfromcore模型importjson定义
1条回答
网友
1楼 · 发布于 2024-04-29 13:21:17

你好,我自己找到了解决办法, 我在传递正确的规范定义时出错, 当然,我的方法集需要递归。 给你:

def _set_defaults(self, in_spec, out_dict):
    # by default resolve the references
    in_spec = self.spec.deref(in_spec)

    # if there is the key propriety,
    # resolve it directly avoiding useless loop
    if 'properties' in in_spec:
        in_spec = in_spec['properties']

    for k_spec in in_spec:
        if k_spec not in out_dict:
            # if an element defined in the swagger is not presend
            # in the json configuration, there are a lot of probabilities
            # it has a default value defined, let's try...
            try:
                d_value = in_spec[k_spec]['default']
                out_dict[unicode(k_spec, "utf-8")] = d_value
            except KeyError:
                pass

        else:
            if not isinstance(out_dict[k_spec], dict):
                continue
            self._set_defaults(in_spec[k_spec], out_dict[k_spec])

当然,如果有人想要更好的(内置的?)解决方案,请随意评论。 谢谢大家

相关问题 更多 >