python - 如何将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]
解决方案
response = requests.get(pdf.url_link)
这response
是一个Response
类对象,其中包含服务器对 HTTP 请求的响应。为了访问response
正文bytes
(对于非文本请求),您应该使用属性。IE,response.content
response = HttpResponse(response.content, content_type='application/pdf')
推荐阅读
- charts - 从轴上删除十进制值
- css - 使 flex-direction:column flex-wrap:wrap 列表中的每一列不超过它需要的宽度
- python-2.7 - 曲线拟合模型的连接
- angular - 角度路由器路由优先级
- java - 如何创建自定义 Hibernate 会话管理器?
- java - 替代直接 onResume() 调用
- python - 标准化时间序列测量
- r - 无法在 R 的 PlotOnStaticMap 中绘制负经度值
- javascript - [JEST]使用 .toMatchObject 时如何定义可选参数?
- concrete5 - 如何在页面 URL 中添加 .html 扩展名