查看使用MediaFileUpload的示例

时间:2012-07-13 14:22:18

标签: python google-app-engine google-drive-api

有谁知道在哪里可以找到上传本地文件和使用MediaFileUpload获取内容的完整示例代码?

我真的需要看到用于发布的HTML表单和接受它的代码。我把头发拉了出来,到目前为止只得到了部分答案。

谢谢!

3 个答案:

答案 0 :(得分:19)

我在试图找出谷歌API示例中的“MediaFileUpload”来源时发现了这个问题,我最终弄明白了。这是一个更完整的代码示例,我用它来测试Python 2.7。

您需要一个JSON凭据文件才能使用此代码。这是您从Google app / project / thing获得的凭据文件。

您还需要上传文件,我在示例中使用“test.html”。

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload

#Set up a credentials object I think
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials_from_google_app.json', ['https://www.googleapis.com/auth/drive'])

#Now build our api object, thing
drive_api = build('drive', 'v3', credentials=creds)

file_name = "test"
print "Uploading file " + file_name + "..."

#We have to make a request hash to tell the google API what we're giving it
body = {'name': file_name, 'mimeType': 'application/vnd.google-apps.document'}

#Now create the media file upload object and tell it what file to upload,
#in this case 'test.html'
media = MediaFileUpload('test.html', mimetype = 'text/html')

#Now we're doing the actual post, creating a new file of the uploaded type
fiahl = drive_api.files().create(body=body, media_body=media).execute()

#Because verbosity is nice
print "Created file '%s' id '%s'." % (fiahl.get('name'), fiahl.get('id'))

可在“body”哈希中使用的有效Mime类型列表 https://developers.google.com/drive/v3/web/mime-types

MediaFileUpload的有效mimetype字符串列表(他们将尝试将您的文件转换为您在此放置的任何内容):

https://developers.google.com/drive/v3/web/integrate-open#open_files_using_the_open_with_contextual_menu

答案 1 :(得分:0)

您不需要自己发布JSON,客户端库会为您处理。

我们已提供完整的代码示例,可在此处找到:https://github.com/gsuitedevs/python-samples

您还可以查看包含Python示例的file.insert参考文档:https://developers.google.com/drive/v2/reference/files/insert

如果这不符合您的要求,您可以更详细地解释您想要实现的目标和当前的架构。

答案 2 :(得分:0)

Python 2.7,可恢复上传。

https://github.com/googleapis/google-api-python-client/blob/master/docs/media.md

$ repo forall -pc "git status -sb"
...
project <project1 root dir>/
## feature/feature_release...origin/feature/feature_release [ahead 1]

project <project2 root dir>/
## HEAD (no branch)

project <project3 root dir>/
...
相关问题