python - 权限错误: [Errno 13] Permission denied | WeasyPrint

标签 python django python-3.x django-1.10

我使用 WeasyPrint 应用程序在我的 django 项目中生成 pdf 文件。

我有下一个代码会引发错误。在我看来,主要问题在这一行output = open(output.name, 'r')。我认为用户没有访问权限。如何解决这个问题?

views.py:

def generate_pdf(request, project_code):
    project = get_object_or_404(Project, pk=project_code, status='open')

    html_string = render_to_string('project/pdf.html', {'project': project})
    html = HTML(string=html_string)
    result = html.write_pdf()

    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=technical_specification.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'r')  <-- ERROR
        response.write(output.read())
    return response

错误:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1808, in generate_pdf
    output = open(output.name, 'r')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nurzhan\\AppData\\Local\\Temp\\tmp_vx7wo99'

我还有这样的警告:

WARNING: @font-face is currently not supported on Windows

最佳答案

pdf 输出不需要写入和读取文件,您只需将其写入响应即可:

def generate_pdf(request, project_code):
    project = get_object_or_404(Project, pk=project_code, status='open')
    template = loader.get_template('project/pdf.html')
    html = template.render(RequestContext(request, {'project': project}))
    response = HttpResponse(content_type='application/pdf')
    HTML(string=html).write_pdf(response)
    return response

如果您确实需要在响应之前将其写入某处,请尝试将 output = open(output.name, 'r') 替换为 output.seek(0)

关于python - 权限错误: [Errno 13] Permission denied | WeasyPrint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44176684/

相关文章:

python - 如何让参与者在Python中按下特定的数字键?

python ROUND_05UP

python - "return"和 "return None"生成器中的行为差异

python - 如何使用 Pyglet 播放音频(在生成器循环中)?

python-3.x - 当我执行 "rasa init"错误 : "failed to install native tensorflow runtime"

python - 如何在 pandas DataFrame 中查找特定列的重复行,并通过添加计数器来修改值?

python - 为什么opencv-python的cv2.bitwise_and函数在单个标量值上返回四个元素数组

python - 如何根据其他列的值估算 NaN 值?

javascript - 插入 csrf token 以进行文件上传

python - Django 上传文件验证导致 "InMemoryUploadedFile is not supported"