【问题标题】:How can I solve this specific python circular import? [duplicate]如何解决这个特定的 python 循环导入? [复制]
【发布时间】:2020-05-07 15:22:36
【问题描述】:

有人可以帮我解决这个 python 循环导入吗?

文件measurement_schema.py 导入elementary_process_schema。并且文件elementary_process_schema.py 导入measurement_schema

我需要在每个声明的类的最后一行使用引用的类。例如:measurement_schema.py的最后一行:elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

完整代码:

measurement_schema.py

from marshmallow import fields

from api import ma
from api.model.schema.elementary_process_schema import ElementaryProcessSchema


class MeasurementSchema(ma.Schema):


    id = fields.Int(dump_only=True)
    name = fields.Str()
    description = fields.Str()
    created_on = fields.Str()

    elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

elementary_process_schema.py

from marshmallow import fields

from api import ma
from api.model.schema.ar_rl_schema import ARRLSchema
from api.model.schema.data_item_schema import DataItemSchema
from api.model.schema.elementary_process_type_schema import ElementaryProcessTypeSchema
from api.model.schema.measurement_schema import MeasurementSchema


class ElementaryProcessSchema(ma.Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()
    operation = fields.Str()
    reference = fields.Str()
    created_on = fields.Str()

    elementary_process_type = fields.Nested(ElementaryProcessTypeSchema)
    data_itens = fields.Nested(DataItemSchema, many=True)
    AR_RLs = fields.Nested(ARRLSchema, many=True)

    measurement = fields.Nested(MeasurementSchema)

我知道有很多关于这个问题的话题。但是,我无法解决我的特定循环引用问题。

【问题讨论】:

  • 您是否探索过在这里实现工厂模式,这是一个示例 mehulkar.com/blog/2017/04/… - 在您的课程中,您可能需要在 MeasurementSchema 中注入 ElementaryProcessSchema,反之亦然。
  • 谢谢侯赛因。我用了smassey的小费。它很简单,效果很好

标签: python marshmallow


【解决方案1】:

这是 ORM 的一个常见问题,而对于 python,它通常以相同的方式解决:您通过名称(字符串)而不是引用(类/实例)来识别关系。它在 marshmallows doc 中有很好的记录:

https://marshmallow.readthedocs.io/en/stable/nesting.html#two-way-nesting

简而言之,尝试这样的事情(我对棉花糖的经验为 0,所以这绝不是经过测试的):

elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)
# would become:
elementary_processes = fields.Nested("ElementaryProcessSchema", many=True)

measurement = fields.Nested(MeasurementSchema)
# becomes:
measurement = fields.Nested("MeasurementSchema")

【讨论】:

  • 另外,我应该包括“exclude=('boundaries', )”,如下所述:measurement = fields.Nested("MeasurementSchema", exclude=('elementary_processes', ))
猜你喜欢
  • 2016-07-10
  • 2019-10-17
  • 1970-01-01
  • 2012-04-19
  • 2021-02-13
  • 2023-04-07
  • 2023-03-29
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多