python - 如何将 pdf 从 Django HTTP 对象上传到 Google Drive

标签 python django google-drive-api pisa

我使用 pisa 创建 pdf 文档以呈现给用户:

response = HttpResponse()
pisa.CreatePDF(src=html, dest=response, show_error_as_pdf=True)
return response

response.content 包含 pdf。我使用 dropbox-python sdk 来执行此操作:

dropbox_client.put_file(folder_path, response.content)

它似乎将response.content理解为pdf并正确上传文件

我需要对 google-drive-python-api 做同样的事情。此引用(https://developers.google.com/drive/v2/reference/files/insert)显示了一个基本方法,但 MediaFileUpload 似乎在寻找物理文件。还有 MediaIoBaseUpload 但它似乎不接受response.content。我对 file/i/o 的东西不是很熟悉,所以我在这里列出了从 django 到 dropbox 到 G-Drive 的所有内容,希望它能澄清我的使用;希望我没有混淆事情。

最佳答案

Python Google API 工具包中的 apiclient.http 文件包含完全满足您需要的 MediaIoBaseUpload 对象。

只是它需要一个文件句柄或行为类似于文件句柄的东西(fh 参数)。你很幸运:这正是 StringIO 的意思。模块用于:

import StringIO # You could try importing cStringIO which gives better performance
fh = StringIO.StringIO(response.content)
media = MediaIoBaseUpload(fh, mimetype='some/mimetype')
# See https://developers.google.com/drive/v2/reference/files/insert for the rest
<小时/>

MediaInMemoryUpload 也可以做到这一点,但现在已弃用。

关于python - 如何将 pdf 从 Django HTTP 对象上传到 Google Drive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904180/

相关文章:

php - php 中的权限不足 google Drive api oauth2

javascript - 无法使用 Google App Script 上传到 Google Drive 上的子文件夹

Django-tastypie。默认以 JSON 格式输出到浏览器

python - 如何在 scrapy pipelines.py 文件中导入 django 模型

Django使用ForeignKey进行单元测试

python - 在数据框列中应用模糊匹配并将结果保存在新列中

javascript - 在XMLHttpRequest中遵循重定向(302)

python - 属性错误 : module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

python - 每当我更改代码时,Flask 都会将所有人注销

jquery - 将 JSON 对象从 Python 脚本发送到 jQuery?