2017-04-09 13 views
0

Ist jemand mit der Google Drive-API vertraut, um mir mitzuteilen, was ich unten mit meinem Code falsch mache? Ich versuche gerade, eine Datei über die API und ein Dienstkonto auf mein Google-Laufwerk zu übertragen. Wenn ich es laufen, ich eine Datei-ID zu bekommen, aber die Datei doesnt zeigt tatsächlich in meinem Laufwerk, so dass ich habe keine Ahnung, wo die Datei tatsächlich gehen wird ...Python mit Google Drive-API

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')  

Antwort

0

Von Ihrem Beispielskript, dachte ich, dass Python Quickstart einfach zu verstehen ist. So verwendet es Python Quickstart um (https://developers.google.com/drive/v3/web/quickstart/python).

  1. Bitte führen Sie Schritt 1 und Schritt 2 bei Python Quickstart.

  2. Ändern Sie das Beispielskript in Python Quickstart wie folgt.

Von:

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'])) 

An:

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) 

Wenn die Datei hochgeladen wurde, kann JSON folgende erhalten werden. Und Sie können die Datei auf Google Drive sehen.

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