Python 如何定义可为空的响应属性?
我将Python库与我的Swagger规范结合使用,它在一些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应用程
定义中具有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_