如何定义可空的响应属性?

时间:2018-03-28 16:30:34

标签: python swagger swagger-2.0 swagger-codegen

我正在将Python库connexion与我的Swagger规范结合使用,该规范在某些with open (my_file, 'r') as my_probe: for fileLine in my_probe: src_string = fileLine.split() my_list = list(src_string) # The list may contain any number of items if len(my_list) > 3: # Only if lists is longer than 4 items print("Info I need: "+my_list[4]) 中具有Traceback (most recent call last): File "my_script.py", line 70, in <module> print ("Info I need: "+my_list[4]) IndexError: list index out of range 属性。

x-nullable属性实质上是一个polyfill,因为OAS 2.0中缺少对可空属性的支持。但是,大多数框架都在不同程度上支持它。

definitions似乎在参数but not responses中支持此属性。

因此,如果您尝试将x-nullable的回复作为connexionnull设置为x-nullable的回复中的任何商品返回值,则会失败验证并在响应中生成validate_responses

如何在True基于Response body does not conform to specification的Python应用程序(例如从swagger-codegen工具生成的应用程序中)对x-nullable的填充支持最佳?

1 个答案:

答案 0 :(得分:1)

管理以指定custom validator,用于修补传递给它的operation定义中的JSON模式。

from connexion.decorators.response import ResponseValidator

class CustomResponseValidator(ResponseValidator):
    def __init__(self, operation,  mimetype):
        operation.definitions = { name: self.patch_nullable_in_definition(definition) for name, definition in operation.definitions.items() }
        ResponseValidator.__init__(self, operation, mimetype)

    def patch_nullable_in_definition(self, definition):
        definition['properties'] = { key: property_ if '$ref' in property_ else self.patch_nullable_in_property(property_) for key, property_ in definition['properties'].items() }
        return definition

    def patch_nullable_in_property(self, property_):
        if isinstance(property_, dict) and \
           not isinstance(property_, list) and \
           'x-nullable' in property_ and \
           property_['x-nullable'] and \
           'type' in property_:
            if not isinstance(property_['type'], list):
                property_['type'] = [property_['type']]
            if not 'null' in property_['type']:
                property_['type'].append('null')
        return property_