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

2024-06-28 11:02:54 发布

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

我将Python库^{}与我的Swagger规范结合使用,该规范在一些definitions中具有x-nullable属性。在

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

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

因此,如果您试图返回一个带有null的响应,该响应的值为x-nullablevalidate_responses设置为True的响应中返回的任何项的值,则验证将失败,并在响应中生成Response body does not conform to specification。在

在一个基于connexion的Python应用程序(例如从^{}工具生成的应用程序)中,如何才能最好地对x-nullable提供polyfill支持?在


Tags: 规范框架应用程序参数属性swaggernotresponses
1条回答
网友
1楼 · 发布于 2024-06-28 11:02:54

设法指定了一个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_

相关问题 更多 >