无法在没有冗余导入

时间:2016-08-19 21:02:41

标签: python jinja2

我试图在传递单个参数时渲染Jinja2模板。此参数是具有引用第二个对象的方法的对象的实例。我传入Jinja2的对象存储在一个模块中,而引用的对象存储在第二个模块中。渲染发生在第三个模块中。当第一个对象的方法引用第二个对象(global name ... is not defined)时,原始代码会出错。这种方法在Jinja2之外工作正常。这是一个设置场景的简单示例...

jinja2渲染模块如下所示:

from jinja2 import Template
from module1 import *
from module2 import *

def return_rendered():
    otr = ObjectToRender()
    otr.name = 'Just making the instance special!'

    temp_str = open('template.html', 'r')
    template = Template(temp_str.read())
    temp_str.close()

    return template.render(otr=otr)

,模板如下所示:

<p>Here is the output from a super cool method!<p>
{{ otr.get_a_cool_name() }}

要渲染的对象:

# module1
class ObjectToRender(object):
    def __init__(self):
        self.name = ''

    def get_a_cool_name(self):
        rc = ReferencedClass() # fails here with "global name 
                               # 'ReferencedClass' is not defined"
        return rc.make_cool(self.name)

from module2 import *

和引用的类:

# module2
from module1 import *
class ReferencedClass(object):
    def __init__(self):
        self.cool_str = 'SUPER COOL'

    def make_cool(self, in_str):
        return in_str + self.cool_str

你会注意到我已经将模块1和2“互相导入”了。这显然没有必要,但在我的用例中它是。无论如何,我可以通过在使用ReferencedClass之前再次导入第二个类来实现此功能。它看起来像这样:

# module1
class ObjectToRender(object):
    def __init__(self):
        self.name = ''

    def get_a_cool_name(self):
        from module2 import ReferencedClass
        rc = ReferencedClass() # it works! 
        return rc.make_cool(self.name)

from module2 import *

所以,我在没有真正理解为什么它首先不起作用的情况下工作......经典。有谁知道我为什么要第二次导入这个课程?

0 个答案:

没有答案