Python : Google Drive へアップロード

概要

Python から Google Drive へ画像ファイルをアップロードする。
同時に画像参照用の URL を取得。

google-api-python-client と PyDrive (google-api-python-client のラッパー) を使用。

環境

  • Debian Strech
  • Python 3.6.0
    • google-api-python-client
    • PyDrive

事前準備

OAuth クライアント ID の取得

Google APIs にアクセスし、OAuth クライアント ID とクライアントシークレットを発行する。

Google Cloud Platform
Google Cloud Platform lets you build, deploy, and scale applications, websites, and services on the same infrastructure as Google.

Google Drive API の有効化

上記のサイトで Google Drive API を有効にする。

手順は以下のサイトを参照

ゼロからはじめるPython(16) ゼロからはじめるPython 第16回 PythonからGoogleドライブを操作しよう(その1)
Pythonには多様なライブラリが用意されているので、様々な分野で活用することができる。今回は、Pythonからオンラインストレージの「Googleドライブ」を操作してみよう。PythonからGoogleドライブにアクセスできれば、任意のタイミングでクラウドにデータをアップしたり、定期的にファイルを更新したり、とアイデ...

コード

upload_gd_image.py

import sys
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

def upload_gd_image(filename):
    FOLDER_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

    gauth = GoogleAuth()
    gauth.CommandLineAuth()
    drive = GoogleDrive(gauth)

    f = drive.CreateFile({'title': os.path.basename(filename),
                          'mimeType': 'image/png',
                          'parents': [{'kind': 'drive#fileLink', 'id': FOLDER_ID}]})

    f.SetContentFile(filename)
    f.Upload()

    url = 'http://drive.google.com/uc?export=view&id=' + f['id']
    return url

if __name__ == '__main__':
    url = upload_gd_image(sys.argv[1])
    print(url)

FOLDER_ID は保存したいフォルダのフォルダIDに書き換える。

フォルダIDはブラウザでそのフォルダを開いた URL の末尾の文字列を見れば分かる。

setting.yaml

client_config_backend: settings
client_config:
  client_id: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  client_secret: xxxxxxxxxxxxxxxxxxxx

save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json

get_refresh_token: True

oauth_scope:
  - https://www.googleapis.com/auth/drive.file
  - https://www.googleapis.com/auth/drive.install

client_id と client_secret を事前に取得した「クライアント ID」と「クライアントシークレット」に書き換える。

関数仕様

ex.
url = upload_gd_image('test.png')
  • 引数
    • filename: ファイルパス
  • 戻値
    • 画像参照用 URL

テスト

test.png をスクリプトと同じディレクトリに置いて実行。

$ python3 upload_gd_image.py test.png
http://drive.google.com/uc?export=view&id=xxxxxxxxxxxxxxxxxxxxxxxxxxx

コメント

タイトルとURLをコピーしました