Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何定义可为空的响应属性?_Python_Swagger_Swagger 2.0_Swagger Codegen - Fatal编程技术网

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

Python 如何定义可为空的响应属性?,python,swagger,swagger-2.0,swagger-codegen,Python,Swagger,Swagger 2.0,Swagger Codegen,我将Python库与我的Swagger规范结合使用,它在一些定义中具有x-nullable属性 此x-nullable属性本质上是一个polyfill,因为在中不支持可为null的属性。然而,大多数框架在不同程度上支持它 connexion似乎在参数中支持此属性 因此,如果您尝试返回带有null的响应,作为x-nullable和validate\u responses设置为True的响应中返回的任何项的值,则验证将失败,并在响应中生成响应体不符合规范 在基于connexion的Python应用程

我将Python库与我的Swagger规范结合使用,它在一些
定义中具有
x-nullable
属性

x-nullable
属性本质上是一个polyfill,因为在中不支持可为null的属性。然而,大多数框架在不同程度上支持它

connexion
似乎在参数中支持此属性

因此,如果您尝试返回带有
null
的响应,作为
x-nullable
validate\u responses
设置为
True
的响应中返回的任何项的值,则验证将失败,并在响应中生成
响应体不符合规范

在基于
connexion
的Python应用程序(例如从工具生成的应用程序)中,如何最好地实现对
x-nullable
的polyfill支持?

在传递给它的
操作
的定义中指定一个补丁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_