GoogleカレンダーをGoogle App Engineで操作するときはどうすれば良いのかと思い、調べたときのメモ。
■GoogleカレンダーのAPIについて
現在v1〜v3まであるが、v1とv2については、2014/11/17に提供終了とのことなので、v3を使うことにする。
Web上の情報もv1,v2のものが多いため、今後利用するときには注意。
GoogleカレンダーAPIバージョン3登場 - 今までのAPIは非推奨 | マイナビニュース
■Pythonライブラリについて
直接RESTで記載してもいいものの、せっかくライブラリがあるのでそちらを利用する。
Googleカレンダーを扱えるものは2種類ある。
- gdata-python-client - Google Data APIs Python Client Library - Google Project Hosting
- google-api-python-client - Google APIs Client Library for Python - Google Project Hosting
ただし、前者のリンクではv2のサイトに飛ぶことから、v3対応はしていないと考え、今回は後者の「google-api-python-client」を使うことにする。
DownloadにはGAE専用の「google-api-python-client-gae-1.0.zip」があるため、そちらをダウンロードする。
ダウンロードしたら、GAE用のディレクトリ(app.yamlなどと同階層)に、apiclientなどのディレクトリ・ファイルをすべて配置する。
■APIを使う準備
APIを利用するために必要なものを、APIコンソールで取得する。
- Google Play Developer Console
- Authentication Overview - Google APIs Client Library for Python — Google Developers
なお、GoogleAppEngineで使う場合は、「Redirect URIs」がアプリのURLになっていなくても動作したが、合わせておいた方が良い気がする。
また、開発サーバーでは動かすことができなかったため、本番環境でテストをした(何か設定が足りないのかもしれない)。
■使い方
あとは公式ドキュメントを参考に実装する。
- Using Google App Engine - Google APIs Client Library for Python — Google Developers
- Google Calendar API - Google Apps Platform — Google Developers
GoogleAppEngine版ではないが、日本語のわかりやすいソースは、以下。
■ソース
calenarhandler.pyのみ、gistへ。
app.yaml
application: <your application id> version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: / script: calendarhandler.app
client_id: '' client_secret: '' calendar_id: ''
calenarhandler.py
# -*- coding: utf-8 -*- import webapp2 import os import yaml from apiclient.discovery import build from oauth2client.appengine import OAuth2Decorator api_key = yaml.safe_load(open('api.yaml').read().decode('utf-8')) decorator = OAuth2Decorator( client_id=api_key['client_id'], client_secret=api_key['client_secret'], scope='https://www.googleapis.com/auth/calendar', ) class CalendarHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): service = build('calendar', 'v3') event = self._create_event() request = service.events().insert( calendarId=api_key['calendar_id'], body=event) http = decorator.http() response = request.execute(http=http) def _create_event(self): event = { 'summary': 'testEvent', 'start': { 'dateTime': '2012-11-17T10:00:00.000', 'timeZone': 'Asia/Tokyo' }, 'end': { 'dateTime': '2012-11-17T11:00:00.000', 'timeZone': 'Asia/Tokyo' }, } return event debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') app = webapp2.WSGIApplication([ ('/', CalendarHandler), (decorator.callback_path, decorator.callback_handler()), ], debug=debug)