2017-04-09 95 views
0

是否有人熟悉Google Drive API,告诉我我的代码在做什么错了?我只是试图使用API​​和服务帐户将文件传输到我的谷歌驱动器。当我运行它,我得到一个文件编号,但该文件实际上本身并没有在我的车出现,所以我不知道该文件的实际发生......带有Google Drive API的Python

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('service_account.json', ['https://www.googleapis.com/auth/drive']) 

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

file_name = "test.html" 
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')  

回答

0

从你的示例脚本,我想Python Quickstart很容易理解。所以它使用Python Quickstart(https://developers.google.com/drive/v3/web/quickstart/python)。

  1. 请在Python Quickstart中执行步骤1和步骤2。

  2. 请按如下方式在Python Quickstart中修改示例脚本。

来自:

1.

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly' 

2.

results = service.files().list(
    pageSize=10,fields="nextPageToken, files(id, name)").execute() 
items = results.get('files', []) 
if not items: 
    print('No files found.') 
else: 
    print('Files:') 
    for item in items: 
     print('{0} ({1})'.format(item['name'], item['id'])) 

到:

1.

SCOPES = 'https://www.googleapis.com/auth/drive.file' 

2.

f = 'test.html' 
mime = 'text/html' 
body = { 
    'name': f, 
    'mimeType': mime 
    # 'parents': ## folderID ##, # If you want to upload file under folder, please use this. 
} 
results = service.files().create(
    body=body, 
    media_body=MediaFileUpload(f, mimetype=mime, resumable=True) 
).execute() 
print(results) 

当文件被上传,以下JSON可以得到。您可以在Google云端硬盘中看到该文件。

{ 
    "mimeType": "text/html", 
    "name": "test.html", 
    "id": "#####", 
    "kind": "drive#file" 
}