Python模板类

Python模板类,python,django,templates,python-2.7,django-templates,Python,Django,Templates,Python 2.7,Django Templates,因此,我想创建一个具有关联模板的类。当我运行类的render()方法时,模板将被处理并作为字符串返回 这就是我到目前为止所做的: class MyClass(): ... def render(self): with open(self._template, O_RDONLY | O_NONBLOCK) as template_file: html = template_file.read() tpl = Template(

因此,我想创建一个具有关联模板的类。当我运行类的render()方法时,模板将被处理并作为字符串返回

这就是我到目前为止所做的:

class MyClass():
    ...
    def render(self):
        with open(self._template, O_RDONLY | O_NONBLOCK) as template_file:
            html = template_file.read()
        tpl = Template(html)
        return tpl.render(self._template_variables)
但这带来了一个错误:

AttributeError: __exit__
我做错了什么

顺便说一句,如果有人对实现这一点有更好的建议,我愿意听取意见。

with operator make close()方法冗余

with operator make close()方法冗余

template_file.close()
不应在
with
语句中调用,因为其目的是自动释放资源。正在抛出
AttributeError
,因为实际上,您要关闭文件两次。

template_file.close()

不应在
with
语句中调用,因为其目的是自动释放资源。正在抛出
AttributeError
,因为实际上,您要关闭文件两次。

我不确定您为什么要复制django中提供的功能;但如果必须,请使用:

我之所以使用,是因为
render\u to\u string
方法采用模板名称,并且您正在向其传递路径


一般来说,避免硬编码,比如文件系统路径,因为它会降低代码的可移植性。

我不知道为什么要复制django中提供的功能;但如果必须,请使用:

我之所以使用,是因为
render\u to\u string
方法采用模板名称,并且您正在向其传递路径


一般来说,避免硬编码,比如文件系统路径,因为这样会降低代码的可移植性。

删除close()并不能解决问题。我仍然有同样的错误。它说它是以“with”开头的:/我不认为进一步调试代码是可能的,除非您提供更多的数据。不管怎样,我还是按照Burhan Khalid的建议去做。删除close()并不能解决问题。我仍然有同样的错误。它说它是以“with”开头的:/我不认为进一步调试代码是可能的,除非您提供更多的数据。不管怎样,我还是按照伯汉·哈立德的建议去做。它是一个包含“/full/path/to/project/templates/the_template.html”的属性,它是一个包含“/full/path/to/project/templates/the_template.html”的属性。是的,这就是为什么如果有人有更好的想法,我会感到难过的原因,因为我对Python和Django还很陌生。这个render_to_string函数帮助了我,现在一切正常。至于完整路径,它不是硬编码的,而是计算为完整路径,如下所示:
PROJECT\u path=path.realpath(path.dirname(\uu file\uuuu))TEMPLATES\u path=PROJECT\u path+'/TEMPLATES'
,然后在我的类“构造函数”中,我像这样传递模板路径:
MyClass(TEMPLATES\u path+'/the\u template.html')
确保通过
模板.html
而不是
/模板.html
。是的,这就是为什么我很难过如果有人有更好的想法,我对它持开放态度,因为我对Python和Django非常陌生。这个render_to_string函数帮助了我,现在一切正常。至于完整路径,它不是硬编码的,而是计算为完整路径,如下所示:
PROJECT\u path=path.realpath(path.dirname(\uu file\uuuu))TEMPLATES\u path=PROJECT\u path+'/TEMPLATES'
,然后在我的类“构造函数”中,我像这样传递模板路径:
MyClass(TEMPLATES\u path+'/the\u template.html')
确保通过
模板.html
,而不是
/模板.html