在我在Heroku上托管的django应用程序中,我有一个视图可以从LaTeX模板生成PDF,并将其存储为临时文件。视图是:
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from subprocess import Popen, PIPE
import tempfile
import os
def pdf(request):
context = Context({})
template = get_template('cv/simple.tex')
rendered_tpl = template.render(context).encode('utf-8')
with tempfile.TemporaryDirectory() as tempdir: ## ERROR RAISED HERE ##
process = Popen(
['pdflatex', '-output-directory', tempdir],
stdin=PIPE,
stdout=PIPE,
)
process.communicate(rendered_tpl)
with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f:
pdf = f.read()
r = HttpResponse(content_type='application/pdf')
r.write(pdf)
return r
这在本地工作正常。但是,当我将其推送到Heroku并尝试访问指向该视图的URL时,出现以下错误:
Internal Server Error: /cv.pdf
Traceback (most recent call last):
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/cv/views.py", line 34, in pdf
with tempfile.TemporaryDirectory() as tempdir:
AttributeError: 'module' object has no attribute 'TemporaryDirectory'
其他有关类似错误的问题表明,这可能是由于具有导入而不是python库的脚本调用
tempfile.py
引起的,但是我没有一个(除非Heroku这样做)。有什么建议么?在此先感谢您的帮助。
最佳答案
TemporaryDirectory在Python 3.2中添加。您应该更新Python以使用此功能。