Pythonを勉強するために、PythonでGoogle Driveにファイル転送スクリプトを作り始めました。実行する度に手動で認証してファイル転送するGoogleのサンプルプログラムがあるので、それを改造して自動処理できるように、認証情報をファイルに入出力するスクリプトを作りました。
毎回手動で認証するサンプルスクリプト
drive.py : Google Drive SDK Python Quickstart Sample
Pythonの基礎
ドットインストールさんのPython基礎講座を見たのでPythonの雰囲気が分かりました。短時間でスタートアップできるので、とても助かります。
あとは、やりたいことをぐぐって、必要なことは公式サイトで確認すればなんとかなりそうです。
Google Driveの認証情報
GoogleのドキュメントにあるRetrieving and Using OAuth 2.0 Credentialsのサンプルコードのコメントを見ると、認証情報はjson形式に変換して格納しろと書いてあります。
def get_stored_credentials(user_id):
"""Retrieved stored credentials for the provided user ID.
Args:
user_id: User's ID.
Returns:
Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To instantiate an OAuth2Credentials instance from a Json
# representation, use the oauth2client.client.Credentials.new_from_json
# class method.
raise NotImplementedError()
def store_credentials(user_id, credentials):
"""Store OAuth 2.0 credentials in the application's database.
This function stores the provided OAuth 2.0 credentials using the user ID as
key.
Args:
user_id: User's ID.
credentials: OAuth 2.0 credentials to store.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To retrieve a Json representation of the credentials instance, call the
# credentials.to_json() method.
raise NotImplementedError()
・store_credentials()
To retrieve a Json representation of the credentials instance, call the credentials.to_json() method
・get_stored_credentials()
To instantiate an OAuth2Credentials instance from a Json representation, use the oauth2client.client.Credentials.new_from_json class method.
認証情報のファイル入出力スクリプト
json形式の認証情報を受け取ってファイルに書き込む関数storeJsonCredential()と、ファイルに保管された認証情報を返すreadJsonCredential()を作りました。
# coding: UTF-8 CREDENTIAL_FILE = 'jsonCredential.txt' def storeJsonCredential(jsonStr): f = open(CREDENTIAL_FILE, 'w') f.write(jsonStr) f.close() def readJsonCredential(): f = open(CREDENTIAL_FILE) json_credential = f.read() f.close() return json_credential
記述方法は、PHPなんかと同じ感じですね。
このモジュールを使って、Googleのサンプルスクリプトを改造していこうと思います。
Pythonスクリプトを作ってみて
ステートメントの区切りがないのが不思議な感じです。ついつい、”;”とか、”}”とかを入力してしまいそうになります。右手の小指が行き場を失って、空中で痙攣しています(笑)
この書き方に慣れると、きっととても楽なんでしょうね。
関連記事
- 2013/01/24 Google Drive APIのクイックスタート
- 2013/01/28 pythonでGoogle Driveにファイル転送
- 2013/01/31 pythonで日付によるファイルの選別
- 2013/02/03 pythonでGoogle Driveにリモートバックアップ