I want a script for a job that regularly uploads files to google drive with python. If you search, there are many articles that use PyDrive, but PyDrive is not well maintained, and it seems that it is not a good idea to use it now because it uses v2 of Google Drive API. This time I will implement it using GoogleDrive API.
Python Quickstart --Grasp the atmosphere of Google Drive API --In this example, you need to log in to the console once. --As for this specification, we want to perform regular uploads without user actions such as console login, so we need to consider another authentication.
Upload file data --File upload sample --There aren't many Python samples, so it doesn't look right.
--A sample using a GCP service account is introduced. ――This qiita article was the most helpful
sample.py
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from oauth2client.service_account import ServiceAccountCredentials
import os
def uploadFileToGoogleDrive(fileName, localFilePath):
service = getGoogleService()
# "parents": ["****"]Replace this part with the string after the URL of the folder you created in Google Drive.
file_metadata = {"name": fileName, "mimeType": "text/csv", "parents": ["****"] }
media = MediaFileUpload(localFilePath, mimetype="text/csv", resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
def getGoogleService():
scope = ['https://www.googleapis.com/auth/drive.file']
keyFile = 'credentials.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyFile, scopes=scope)
return build("drive", "v3", credentials=credentials, cache_discovery=False)
getGoogleService()
uploadFileToGoogleDrive("hoge", "hige.csv")
Recommended Posts