PermissionError:[Errno 13]权限被拒绝| WeasyPrint

时间:2017-05-25 09:13:26

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

我使用WeasyPrint app在我的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

1 个答案:

答案 0 :(得分:2)

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)