如何将 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 来访问私有 S3 存储库的字段。 我正在尝试创建一个函数来接收模型的 id,通过引用加载它并将其传递给响应以便在 SPA 中进行进一步处理。 基于在堆栈溢出上找到的答案,我编写了以下函数

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

BUt 出现错误

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]
response = requests.get(pdf.url_link)

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

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

最新更新