2017-05-25 355 views
1

我使用WeasyPrint應用程序在我的django項目中生成pdf文件。PermissionError:[錯誤13]權限被拒絕| WeasyPrint

我有下一個代碼引發錯誤。在我看來,這條線上的主要問題是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 

回答

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.seek(0)

+0

謝謝更換output = open(output.name, 'r')!我用這篇文章解決了我的問題。鏈接:http://www.supinfo.com/articles/single/379-generate-pdf-files-out-of-html-templates-with-django –

相關問題