如何通过python API将json/pickle文件转储并读入Google Drive?

alv*_*vas 5 python api json pickle google-drive-api

我从这里下载的开始代码:http://goo.gl/Tcxkod并按照说明操作,安装了sample.py从这里https://developers.google.com/api-client-library/python/start/installation:

alvas@ubi:~/git/UniversalCorpus/drive-cmd-line-sample$ python sample.py
Success! Now add code here.
Run Code Online (Sandbox Code Playgroud)

但是如何将pickle/json文件转储到驱动器上然后检索它以从python中读取?

我点击了开发文档,除了repr和源代码本身之外没有任何线索:https://developers.google.com/resources/api-libraries/documentation/drive/v2/python/latest/drive_v2.files.html #得到

Nil*_*Nil 6

使用 PyDrive

我测试了PyDrive,我认为它非常简单。这是我所做的:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

# Upload a json file (will be identical for a pickle file)
json_file = drive.CreateFile()
json_file.SetContentFile('wopwop.json')
json_file.Upload() # Files.insert()
print json_file['title'], json_file['id']

# Download the same json file
same_json_file = drive.CreateFile({'id': json_file['id']})
same_json_file.GetContentFile('test.json')  # Save Drive file as a local file
Run Code Online (Sandbox Code Playgroud)

这段代码有两个“问题”:

  • 每次使用它时,它都会在浏览器中询问您是否同意。阅读本页,让他记住你的答案。
  • 如您所见,您需要记住文件的唯一标识符 (id)。您可以将它们放在数据库或本地 json 文件中。您还可以使用 PyDrive列出与查询匹配的所有文件,从而为您提供其 ID。

没有 PyDrive

如果你对使用 PyDrive 不感兴趣,我强烈建议你阅读它的代码。如果必须这样做,我会在 pydrive.files 中放置 3 个断点(或打印):

  • _FilesInsert上线self.auth.service.files().insert(**param).execute()
  • _FilesUpdate上线self.auth.service.files().update(**param).execute()
  • _DownloadFromUrl上线self.auth.service._http.request(url),并在构造函数中,看看他是如何获得的URL(它在self.metadata

您已经拥有service在 中下载的代码sample.py,因此您只需要知道param字典中的内容即可了解正在发生的事情。

但是,您应该使用 PyDrive ;)