Swagger 3.0生成的Python SDK无法直接访问嵌套对象属性?
Swagger生成Python SDK后嵌套对象链式访问问题
问题描述
我用Swagger 3.0定义了包含嵌套对象的数据类型,对应的Schema如下:
schemas: singleinput: type: object properties: image: type: object properties: url: type: string example: www.abc.com/001.jpg
生成Python SDK后,我尝试了以下操作:
input = Singleinput() # 此操作正常 input.image.url='xxxxx' # 报错 input.image = {"url":"xxxx"} # 此操作正常
查看SDK源码发现,Singleinput类包含image属性,且存在SingleinputImage类定义,但input.image初始值为None,导致无法使用链式访问。目前我通过显式创建嵌套类实例的方式可以正常操作:
image = SingleinputImage('xxxx') input = Singleinput(image)
想咨询:我的操作方式是否正确?还是Swagger本身不支持访问二级以上属性?
附Singleinput类源码:
Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'image': 'SingleinputImage' } attribute_map = { 'image': 'image' } def __init__(self, image=None): # noqa: E501 """Singleinput - a model defined in Swagger""" # noqa: E501 self._image = None self.discriminator = None if image is not None: self.image = image @property def image(self): """Gets the image of this Singleinput. # noqa: E501 :return: The image of this Singleinput. # noqa: E501 :rtype: SingleinputImage """ return self._image @image.setter def image(self, image): """Sets the image of this Singleinput. :param image: The image of this Singleinput. # noqa: E501 :type: SingleinputImage """ self._image = image
解答
你的操作方式是正确的,Swagger本身完全支持嵌套对象的二级及以上属性访问,问题出在SDK生成工具的实现上:
- 生成的
Singleinput类在初始化时,image属性默认被设为None,所以直接链式调用input.image.url会触发AttributeError(因为None没有url属性)。 - 你目前使用的几种有效操作都是合法的:
- 显式创建
SingleinputImage实例并传入Singleinput的构造函数 - 直接给
image赋值字典(SDK内部应该会自动将字典转换为SingleinputImage实例)
- 显式创建
- 你还可以补充一种操作方式:先初始化
image属性为SingleinputImage实例,再链式赋值:input = Singleinput() input.image = SingleinputImage() input.image.url = 'xxxxx'
总结:这不是Swagger的限制,而是生成的SDK类默认不自动初始化嵌套对象实例导致的,你当前的操作方式完全正确,也可以根据需求选择其他可行的赋值方式。
内容的提问来源于stack exchange,提问作者Xingdi
相关产品推荐
相关产品推荐

