Frage

Trying to use Oauth 2.0 server to server authentication (using a service account) to upload a file to google drive. Have used their sample code as a reference, the resulting script is something like this:

import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.http import MediaFileUpload

def main(argv):
    # Load the key in PKCS 12 format that you downloaded from the Google API
    # Console when you created your Service account.
    f = open('key.p12', 'rb')
    key = f.read()
    f.close()

    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

    # Path to the file to upload
    FILENAME = 'testfile.txt'

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with the Credentials. Note that the first parameter, service_account_name,
    # is the Email address created for the Service account. It must be the email
    # address associated with the key that was created.
    credentials = SignedJwtAssertionCredentials(
        'xxxxx-xxxxxxx@developer.gserviceaccount.com',
        key,
        OAUTH_SCOPE)
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)

    # Insert a file
    media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
    body = {
        'title': 'My document',
        'description': 'A test document',
        'mimeType': 'text/plain'
    }

    fil = drive_service.files().insert(body=body, media_body=media_body).execute()
    pprint.pprint(fil)

if __name__ == '__main__':
main(sys.argv)

The script seems to run ok (no errors, pprint shows output that seems to be fine). However the google drive page for the account does not show the uploaded file. When trying to access one of the links from the pprint output to see the file I get a "You need permission" message from Google Drive, which is weird, as I am logged to the account in which I created the service account.

War es hilfreich?

Lösung

The file is owned by the service account, not your Google account. Service accounts have their own 5gb of space for Google Drive.

You'll need to either share the file with your user account or have the service account impersonate your user account (assuming you're in a Google Apps domain) so that the file is created and owned by your user account.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top