/generate-pdf 处的 PermissionError [Errno 13] 权限被拒绝 weasyprint

PermissionError at /generate-pdf [Errno 13] Permission denied weasyprint

你好,我正在使用 weasyprint 生成 pdf 我的代码有什么问题,访问被拒绝。

def generate_pdf(request):
    """Generate pdf."""
    # Model data
    student = Student.objects.all().order_by('last')

    # Rendered
    html_string = render_to_string('pdf-output.html', {'student': student})
    html = HTML(string=html_string)
    result = html.write_pdf()

    # Creating http response
    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=list_os_students.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'rb')
        response.write(output.read())

    return response

如果我将行 output = open(output.name, 'rb') 更改为 output = open(output.seek(0), 'rb'),则在控制台打印时页面会加载到无穷大

[22/Oct/2020 11:36:54] "GET /dashboard HTTP/1.1" 200 84413
Not Found: /assets/media/avatars/avatar15.jpg
[22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar15.jpg HTTP/1.1" 404 2917
Not Found: /assets/media/avatars/avatar2.jpg
[22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar2.jpg HTTP/1.1" 404 2914
Not Found: /assets/media/avatars/avatar1.jpg
Not Found: /assets/media/avatars/avatar13.jpg
[22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar1.jpg HTTP/1.1" 404 2914
Not Found: /assets/media/avatars/avatar11.jpg
[22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar13.jpg HTTP/1.1" 404 2917
[22/Oct/2020 11:36:54] "GET /assets/media/avatars/avatar11.jpg HTTP/1.1" 404 2917

回溯

Traceback (most recent call last):
  File "C:\Users\cipher\Python\Django\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\cipher\Python\Django\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\cipher\Python\Django\sis\dashboard\views.py", line 72, in generate_pdf
    output = open(output.name, 'rb')

Exception Type: PermissionError at /generate-pdf
Exception Value: [Errno 13] Permission denied: 'C:\Users\cipher\AppData\Local\Temp\tmp996pqacl'

经过几个小时的努力,我已经能够避免错误,希望它能帮助其他人too.I 将行 output = open(output.name, 'rb') 替换为行 output.seek(0) 看起来像

 response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=list_of_students.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output.seek(0)
        response.write(output.read())

    return response

就我个人而言,我不知道为什么,我更喜欢问题中所问的访问不被拒绝的解决方案,如果您碰巧有答案或解释,请分享。