Googleのサンプルスクリプトを改造してGoogle Driveにファイルをアップロードするスクリプトを作りました。
Goolgeのサンプルスクリプトでは、実行する度に手動で認証処理をする必要があったので、1度だけ認証処理をして、2回目以降は1回目の認証情報を使うようにしました。
スクリプト
■ transferToGdrive.py
ファイルをGoogle Driveに転送するスクリプトです。
#!/usr/bin/python
# coding: UTF-8
import httplib2
from oauth2client.client import OAuth2WebServerFlow
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
import googleDriveAccess
import logging
logging.basicConfig()
CLIENT_ID = '******.apps.googleusercontent.com'
CLIENT_SECRET = '*********'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
def first_authorize():
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
googleDriveAccess.store_credentials(credentials)
return credentials
def upload_file(filename, file_mimetype):
logging.getLogger().setLevel(getattr(logging, 'ERROR'))
try:
credentials = googleDriveAccess.get_stored_credentials()
if credentials is None or credentials.invalid:
credentials = first_authorize()
except Exception, e:
credentials = first_authorize()
# Connect to Google Drive
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
# Upload a file
media_body = MediaFileUpload(filename, mimetype=file_mimetype, resumable=True)
body = {
'title': filename,
'description': 'sakuraVPS',
'mimeType': file_mimetype
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
upload_filename = 'document.txt'
upload_file_mimetype = 'text/plain'
upload_file(upload_filename, upload_file_mimetype)
次の部分を設定する必要があります。
- CLIENT_ID = ‘******.apps.googleusercontent.com’
- CLIENT_SECRET = ‘*********’
設定する値は、https://code.google.com/apis/consoleで作成したOAuth 2.0 client の値を設定します。
(”API Access” > “Create an OAuth 2.0 client ID…”から“Installed application”を指定して作成)
スクリプト内では、サンプルスクリプトと同じ固定のファイルを転送するようにしています。
■ googleDriveAccess.py
認証情報をファイルに保存・読み出しするモジュールです。transferToGdrive.pyで使っています。
import httplib2
import oauth2client.client
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
def get_stored_credentials():
"""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.
"""
json_credential = readJsonCredential()
return oauth2client.client.Credentials.new_from_json(json_credential)
def store_credentials(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.
"""
json_credential = credentials.to_json()
storeJsonCredential(json_credential)
ログレベルの設定
Googleのサンプルスクリプトを実行すると、次のようなエラーがでました。
ぐぐってみると、ログ出力して解決する必要があるとのことだったので、次のステートメントでログ出力してみました。
import logging logging.basicConfig()
すると、こんなログがでました。
WARNING:oauth2client.util:__init__() takes at most 4 positional arguments (5 given)
ログの意味はよくわかりませんが、自分の制御範囲外のところで出ているWarningで、エラーでもないので次のステートメントでWarningは出力しないようにしました。
logging.getLogger().setLevel(getattr(logging, 'ERROR'))
使い方
1回目に実行すると、次のように認証コードの入力待ちになります。
Go to the following link in your browser: https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=*******.apps.googleusercontent.com&access_type=offline Enter verification code:
ブラウザで、表示されたURLにアクセスします。
「アクセスを許可」ボタンをクリックすると認証コードが表示されます。
この認証コードをコピー&ペーストして入力するとファイル(‘document.txt’)がGoogle Driveに転送されます。
2回目以降の実行は、認証なしでファイルがGoogle Driveに転送されます。
次のステップ
最終的にバックアップファイルをGoogle Driveに自動で転送したいので、その部分の処理をpythonで作る予定です。
関連記事
- 2013/01/24 Google Drive APIのクイックスタート
- 2013/01/27 pythonでファイル入出力
- 2013/01/31 pythonで日付によるファイルの選別
- 2013/02/03 pythonでGoogle Driveにリモートバックアップ

