Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file to google drive with service account credential

I wanted to upload the files to my Google Drive using a Google service account credentials.

I downloaded credential as a JSON file from Google Developer Console, and got credential from it.

Here is my code snippet.

google_drive_service = discovery.build('drive', 'v3',
          credentials=ServiceAccountCredentials.from_json_keyfile_name
                           os.path.join(settings.CLIENT_PATH, settings.CLIENT_SECRET_FILE),
                           scopes=settings.SCOPES))


media = MediaFileUpload(tmp_file_path, mimetype=tmp_file.content_type, resumable=True)
google_drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()

The code runs and there is no error, however I can't find out the files uploaded to my Google Drive account. I am not sure why files are not uploaded. Would you like to help me to fix this problem?

like image 270
Snipper03 Avatar asked Apr 05 '18 02:04

Snipper03


People also ask

How do I enable Google Drive API and get client credentials?

Enable the Drive APIGo to the Google API Console. Select a project. In the sidebar on the left, expand APIs & auth and select APIs. In the displayed list of available APIs, click the Drive API link and click Enable API.


1 Answers

The issue you are having is that a service account is not you. you have uploaded a file to the service accounts Google drive account not your personal drive account. Try doing a file list you should see the file.

Suggestion. Take the service account email address and share a directory on your personal Google drive account with it like you would share with any other user. The Service account will then be able to upload to this directory. Just make sure to set the permissions on the file after you upload it granting your personal drive account access to the file. When the file is uploaded it will be owned by the service account.

like image 147
DaImTo Avatar answered Oct 16 '22 15:10

DaImTo