この記事では、Google Drive APIとPythonを使用してGoogle Driveにファイルをアップロードする方法を解説します。
関連記事:【Python】Google Drive APIを使ってファイル一覧を取得する方法
環境設定
ライブラリのインストール
まず、以下のコマンドで必要なパッケージをインストールします。
pip install --upgrade google-api-python-client
pip install google-auth
pip install google-auth-oauthlib
pip install google-auth-httplib2
認証情報の作成
Google Cloud Consoleで新しいプロジェクトを作成し、Drive APIを有効にして認証情報(credentials.json)をダウンロードします。
手順について下記の記事で解説しています。
関連記事:【GCP】GoogleCloudPlatformでプロジェクトを作成してAPI鍵の作成して有効化する
また合わせて下記のURLからGoogle driver API を有効化しておく必要があります
Google Drive APIを使用してファイルの一覧を取得する
以下は、PythonでGoogle Drive APIを使用してファイルの一覧を取得するサンプルコードです。
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
SCOPES = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
r"C:\Users\oruka\~~~~~.json", SCOPES
)
http_auth = credentials.authorize(Http())
drive_service = build('drive', 'v3', http=http_auth)
画像ファイルをアップロードするサンプルコード
from apiclient.http import MediaFileUpload
folder_id = '<アップロード先のフォルダID>'
file_metadata = {
'name': '<アップロード時のファイル名>.jpg',
'parents': [folder_id]
}
media = MediaFileUpload(
"<ローカルの画像のPATH>.jpg",
mimetype='image/jpeg',
# resumable=True
)
file = drive_service.files().create(
body=file_metadata, media_body=media, fields='id'
).execute()
#fieldに指定したidをfileから取得できる
print ('File ID: %s' % file.get('id'))
resumable=Trueを指定すると「EOF occurred in violation of protocol ~~~」みたいなエラーが発生したのでコメントアウトしています。画像以外にテキストや動画をアップロードする場合は「mimetype=’image/jpeg’,」の部分を適切なものに変更してください
MINE TYPEの参照:https://www.tohoho-web.com/wwwxx015.htm
ファイル,フォルダの削除
(認証処理)
~~~
file = drive_service.files().delete(
fileId='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
).execute()
#fieldに指定したidをfileから取得できる
print('File ID: %s' % file.get('id'))

コメント