首页 > 解决方案 > 如何将pdf文件添加到django响应

问题描述

我有一个模型,其中包含指向存储在 AWS S3 中的文件的链接。

class Documents(models.Model):
    """ uploaded documents"""

    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    filedata = models.FileField(storage=PrivateMediaStorage())
    filename = models.CharField(_('documents name'), max_length=64)
    created = models.DateTimeField(auto_now_add=True)
    filetype = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True)
    url_link = models.URLField(default=None, blank=True, null=True)

url_link是使用来自 boto3 的预签名 URL 的字段,用于访问 privat S3 存储库。我正在尝试创建一个函数来接收模型的 id,通过引用加载它并将其传递给响应,以便在 SPA 中进行进一步处理。根据在stackoverflow上找到的答案,我编写了以下函数

def view_pdf(request, pk):
    pdf = get_object_or_404(Documents, pk=pk)
    response = requests.get(pdf.url_link)
    with open(response, 'rb') as pdf:
        response = HttpResponse(pdf.read(), mimetype='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response
    pdf.closed

但是出错了

TypeError at /api/v1/files/pdf/90
expected str, bytes or os.PathLike object, not Response

错误回溯

Internal Server Error: /api/v1/files/pdf/90
Traceback (most recent call last):
  File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/y700/projects/healthline/lifeline-backend/apps/files/views.py", line 68, in view_pdf
    with open(response, 'rb') as pdf:
TypeError: expected str, bytes or os.PathLike object, not Response
HTTP GET /api/v1/files/pdf/90 500 [1.06, 127.0.0.1:57280]

标签: pythondjango

解决方案


response = requests.get(pdf.url_link)

response是一个Response类对象,其中包含服务器对 HTTP 请求的响应。为了访问response正文bytes(对于非文本请求),您应该使用属性。IE,response.content

response = HttpResponse(response.content, content_type='application/pdf')

推荐阅读