如何将 pdf 从 Django HTTP 对象上传到谷歌云端硬盘



我使用 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也可以解决问题,但现在已弃用。

最新更新