LoginSignup
1
2

More than 1 year has passed since last update.

pyDriveを使わずにpythonでGoogleDriveを使ってみた

Posted at

やったこと

自前のラップファイルを作成して、pyDriveを使わずにGoogleDriveにファイルをアップロード,
ダウロード、ファイル削除を行った。
pyDriveを使用しないことで汎用性を実現した。(はず)

事前知識

pyDriveとは

pythonでGoogleDriveを使うときによく使われるラッパーライブラリ。ラッパーとある通り、すでに提供されている様々なライブラリをラップする形で作られている。とりあえずpythonでGoogleDriveを使いたいっていう人は便利。でも、汎用性に欠ける(個人の意見)

私が書いたコードの目的

GoogleDriveにファイルを一時保存し別の場所から抜き取るという作業を行うための書いた。そのためファイル移動とかの部分は書いてない。

準備

GCPから接続用の秘密鍵を取得

クライアント接続用のJsonファイルを事前にダウロードしておく。

ライブラリのインストール

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client

ラップファイル

GoogleDrivefunc.py
# https://console.cloud.google.com/getting-started

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client import file, client, tools
from httplib2 import Http
import os
import io

#MP3:mimeType="audio/mpeg"
#WAV:mimeType="audio/wav"

def getGoogleService(keyFile):
    SCOPES = ['https://www.googleapis.com/auth/drive']
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets(keyFile, SCOPES)
        creds = tools.run_flow(flow, store)
    return build('drive', 'v3', http=creds.authorize(Http()))

def deletefileinGoogleDrive(deletefileID, keyFile):
    service = getGoogleService(keyFile)
    file = service.files().delete(fileId=deletefileID).execute()
    #print("Deletion Success")

def uploadFileToGoogleDrive(fileName, localFilePath, updirID, keyFile):
    service = getGoogleService(keyFile)
    file_metadata = {"name": fileName, "mimeType": "audio/wav", 'parents': [updirID]}
    media = MediaFileUpload(localFilePath, mimetype="audio/wav", resumable=True)
    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    #print("File created, id:", file.get("id"))
    #print("Upload Success")
    return (file.get("id"))

def getlistGoogleDrive(keyFile, updirID):
    service = getGoogleService(keyFile)
    list = service.files().list(q="'"+ updirID + "' in parents", fields="files(id, name)", pageSize=10, orderBy="name,modifiedByMeTime").execute()
    return (list)

def downloadtoGoogleDrive(downloadfileID, downloadfileName, savedir, keyFile):
    service = getGoogleService(keyFile)
    request = service.files().get_media(fileId=downloadfileID)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fd=fh, request=request)
    done = False
    while not done:
        status, done = downloader.next_chunk()
    with open(savedir+downloadfileName, 'wb') as f:
        f.write(fh.getbuffer())
        f.close()

keyfileを使って接続を確立してから処理を開始する。meta_dataに設定項目がまだ存在していますが、アップロードダウロードの必要最低限のmetadataで実現してます。
削除の関数はゴミ箱にも入らず完全に削除するので注意が必要。
仕様上、ファイルをダウンロードするにはファイルのIDが必要です。

質問・ご意見があれば、その都度記事に追記しますのでコメントをお願いします。

参考元

PythonでGoogleDriveAPIを使ってGoogle Driveにファイルを定期的にアップロードする
mimeTypeの参考元
Google Drive API Delete Python
Google Drive for developers Delete
Python:GoogleDriveAPIの基本的な使い方

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2