简体   繁体   中英

Google drive Python to upload file not working

I'm using below code,fileID is getting generated but file is not uploaded. I tried debugged but it shows same output as code output. I have placed the service account json file and test.csv in the folder where the python code is placed.

from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload




def uploadGdrive():
    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    SERVICE_ACCOUNT_FILE = './iron-tea-266706-8a1f9ee69710.json'
    folder_id = '15xc7s-dFnpW6pjtjtUH4kT1BnZ46ffFh'
    #file_id = '1IcbtXGW1ZMmv64SqqXJZCsFrwMlE3NiQcDZR98XuFX8'
    file_location='./test.csv'

    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = build('drive', 'v3', credentials=creds)
    file_metadata = {
        'name': 'Master Summary',
        'mimeType': 'application/vnd.google-apps.spreadsheet'
    }

    media = MediaFileUpload(
        '{}'.format(file_location),
        mimetype='text/csv',
        resumable=True)

    #This is to update existing file
    #file = service.files().update(body=file_metadata,media_body=media,fileId='{}'.format(file_id)).execute()
    #print(file.get('id'))

    #this is to create new  file
    file = service.files().create(body=file_metadata,
                                   media_body=media,
                                   fields='id').execute()
    print('File ID: %s' % file.get('id'))

if __name__ == '__main__':
    uploadGdrive()

A service account is not you. A service account is a dummy user, it has its own drive account. Files it uploads are owned by it.

Your file is probably being uploaded to the service accounts drive account. or where ever '15xc7s-dFnpW6pjtjtUH4kT1BnZ46ffFh' is assuming that the service account has access to write to that directory. You can see this by doing a file.list and seeing which files it currently has access to.

If the file to create was successful it will return a file.id as part of the response you can check that as well.

You could create a directory on your own google drive account share that directory with the service account. Then have the service account upload files into that directory then you would be able to see them on your own account. You would also need to grant yourself permissions to the file when its uploaded. Look into permissions.create.

Alternatively you could have the service account upload the files to its own account and then add permissions for you to the file so that you would be able to see it. Look into permissions.create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM