Search code examples
pythongoogle-drive-apiservice-accounts

google drive upload via python api unattended


i have a requirement to upload video files to google drive unattended. i want to use google drive api. but the problem is that

  1. if i use service account, googe is creating a service account email and asking me to share a folder to upload files. So my google drive is not the owner of the file. And we are not sure where these files are being stored
  2. if i use oauth method its populating a webpage for login and tokens are perishing quickly which can't be useful for unattended execution.

When i ran below code to impersonate email i am getting error.

import googleapiclient.discovery
from google.oauth2.service_account import Credentials

# Load service account credentials from JSON key file
SERVICE_ACCOUNT_KEY_FILE = 'apikeys.json'
SCOPES = ['https://www.googleapis.com/auth/drive']

def impersonate_user(user_email):
    credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_KEY_FILE, scopes=SCOPES)
    credentials = credentials.with_subject(user_email)
    return credentials

def upload_file_to_drive(credentials, file_path, folder_id):
    drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)

    file_metadata = {'name': 'my_video.mp4', 'parents': [folder_id]}
    media = googleapiclient.http.MediaFileUpload(file_path, mimetype='video/mp4')
    uploaded_file = drive_service.files().create(
        body=file_metadata, media_body=media, fields='id').execute()

    print(f'File uploaded with ID: {uploaded_file["id"]}')

if __name__ == '__main__':
    # Replace with the user's email and target folder ID
    user_email = '[email protected]'
    target_folder_id = '1unzEKIYnXnBlYEaJxIEiWpHM2MA-Du6D'
    video_file_path = r'C:\Users\M000747\OneDrive - Osara Technologies Limited\Desktop\coding\zoom_download\2024-02-27_17-44-15\CSEC Integrated Science\CSEC Integrated Science_shared_screen_with_speaker_view_2024-02-24T22_35_06Z.mp4'

    user_credentials = impersonate_user(user_email)
    upload_file_to_drive(user_credentials, video_file_path, target_folder_id)```

Error:
 raise exceptions.RefreshError(
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})

kindly help


Solution

  • As u said u can use the oauth method but here's how it works:

    -->Initially, you authenticate your application using OAuth 2.0, which involves obtaining an access token and a refresh token.The access token is used to make requests to the Google Drive API on behalf of the user.

    -->Everytime the access token expires, you use the refresh token to obtain a new access token without needing the user to re-authenticate.You continue using the new access token to make requests to the Google Drive API.

    -->If the refresh token expires (which is after a long time), you'll need to re-authenticate your application with the user.