(Python, no error but doesn't work) Google drive API can't upload file

30 Views Asked by At

Recently I am doing my side project, hoping to upload a excel file to my Google drive account by using Python. I use the code chatGPT suggested, however, there is no error in the code but I just could not successfully upload the file (could not find the file in my drive)

I hope there are experts who can help with the answer, thank you very much!

Here are my codes:

import os
import datetime
from google.oauth2 import service_account
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

path_JSON = r'C:\Users\CY Chang\OneDrive\Desktop\coding\SideProjects\automate-update-excel-files-76a7ac1bd37f.json'
path_file = r'C:\Users\CY Chang\OneDrive\Desktop\filefolder\file\updatedfile.xlsx'

try:
    # Setting Google Drive API cred
    credentials = service_account.Credentials.from_service_account_file(
        path_JSON,
        scopes=['https://www.googleapis.com/auth/drive']
    )

    # Setting Google Drive API
    drive_service = build('drive', 'v3', credentials=credentials)

    # Create Google Drive catalog
    folder_metadata = {
        'name': 'Daily_Uploads',
        'mimeType': 'application/vnd.google-apps.folder'
    }
    folder = drive_service.files().create(body=folder_metadata, fields='id').execute()
    folder_id = folder.get('id')

    # Upload Excel file to Google Drive
    file_metadata = {
        'name': f'Daily_Upload_{datetime.date.today()}.xlsx',
        'parents': [folder_id]
    }
    media = MediaFileUpload(path_file, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()

    print(f'File ID: {file.get("id")}')

except Exception as e:
    print(f'Error: {e}')

  • Currently I had tried:
  1. Checked out my Google Drive API.Since I tried many times, there are 40 requests and no errors. (https://i.stack.imgur.com/eIOF9.png)

  2. Checked out my Goole Drive API access rights. My assigned role for myself is"owmer", should I add something like editor?(https://i.stack.imgur.com/Fx8dP.png)

  3. Also I had tried the others solutions chatGPT provided, such as checking JSON file, but it doesn't work.

0

There are 0 best solutions below