Python和Swagger 2-嵌套对象的导入类无法正常工作

问题描述 投票:0回答:1

我对从Swagger-Codegen生成的代码有问题。

我用Swagger创建了以下对象定义:

...
definitions:
  Object1:
    type: "object"
    properties:
      id:
        type: "integer"
        format: "int64"
      obj2:
        $ref: "#/definitions/Object2"
  Object2:
    type: "object"
    properties:
      id:
        type: "integer"
        format: "int64"
      name:
        type: "string"
...

然后我导出了YAML文件,并为python-flask生成了存根服务器。

当我尝试启动flask服务器时,出现错误:

NameError: name 'Object2' is not defined

__init__.py文件是自动生成的,并且包含两个模型的类的导入:

from swagger.models.object1 import Object1
from swagger.models.object2 import Object2

如果将导入添加到Object2类中,则会出现此错误:

object1.py

from swagger.models import Object2
ImportError: cannot import name 'Object2' from partially initialized module 'swagger.models' (most likely due to a circular import)

仅当我将此导入添加到object1.py时,该错误才能解决:

from swagger.models.object2 import Object2

由于生成了代码,并且所有更改都将丢失,是否可以导入Object2类?

我尝试编辑model.mustache模板,但找不到找到允许导入所需模型的方法。

感谢任何可以帮助我的人。

python-3.x flask swagger-2.0 swagger-codegen
1个回答
0
投票

我遇到了类似的问题,问题在于,大张旗鼓地将所有导入都创建为绝对导入,这不适用于软件包。您需要的是相对导入

而不是:from swagger.models.entity import Entity

您应该这样做:from .entity import Entity

© www.soinside.com 2019 - 2024. All rights reserved.