【问题标题】:How to validate a json with bravado-core against swagger and set the default value in python如何使用 bravado-core 对 swagger 验证 json 并在 python 中设置默认值
【发布时间】:2018-02-04 02:20:41
【问题描述】:

我已经定义了一个 swagger 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-core 模块 (handle_null_value),但目前没有运气。

我最终尝试循环进入 json 对象及其相关定义,例如:

def set_defaults(in_spec, out_dict):
    in_spec = spec.deref(in_spec)
    pprint.pprint(in_spec)
    pprint.pprint(out_dict)
    for k_spec in in_spec:
        print k_spec
        if k_spec not in out_dict:
            try:
                d_value = in_spec[k_spec]['default']
                out_dict[k_spec] = d_value
            except:
                pass

但我被卡住了,因为我不知道如何取消引用......(当然这样的解决方案应该是递归的)

任何帮助或建议将不胜感激

非常感谢。

【问题讨论】:

    标签: python json swagger


    【解决方案1】:

    您好,我自己找到了解决方案, 我在传递正确的规范定义时出错, 当然我的方法 set_default 需要是递归的。 你在这里:

    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])
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-17
      • 2015-11-18
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多