2017-05-25 357 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 –

相关问题