Heroku Django ApplicationError: 'module' has no attribute 'TemporaryDirectory'

Heroku Django ApplicationError: 'module' has no attribute 'TemporaryDirectory'

在我托管在 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'

关于类似错误的其他问题表明,这可能是由于一个脚本调用 tempfile.py 而不是 python 库被导入,但我没有(除非 Heroku做)。有什么建议吗?

在此先感谢您的帮助。

TemporaryDirectory 添加于 Python 3.2。您应该更新 Python 才能使用此功能。