環境
- Anaconda 2.2
- Python 3.8
前提として、Anaconda(Python)、Djangoのセットアップは済んでいるものとします。
セットアップ
必要な設定を行っていきます。
Google APIの有効化
公式リファレンスに従って、APIを有効化するプロジェクトを作成。
既存のプロジェクトに対してAPIを有効化する場合、新規にプロジェクトを作成する必要はない。
https://developers.google.com/workspace/guides/create-project?hl=ja
プロジェクトを作成したら、必要なAPIを有効化する。
既存のプロジェクトを使う場合も有効化は必要。
有効化するのは「Google Calendar API」。
https://developers.google.com/workspace/guides/enable-apis?hl=ja
認証用のCredentialsを取得
公式リファレンスに従って、認証用クレデンシャルを取得する。
- 3種類の認証方法があるが、今回は「OAuth Client ID」を取得する。
- 取得の際の、アプリケーションの種類は「WEBアプリケーション」。
- 認証情報の名前は任意の名前を付ける。公開されないので、自分で管理しやすい名前を。
- 承認済みのリダイレクトURIは、自身のWEBアプリのURIを設定。「このURIから送られたら認証を通してくれ」という意味。Djangoをローカル開発している場合は「http://localhost/」
- 認証情報が作成できたら、credentailsをjsonでダウンロード。credentials.jsonという名前で、実行するコードと同階層に保存。
また、認証が有効になるまで時間がかかる事がある。
https://developers.google.com/workspace/guides/create-credentials?hl=ja
仮想環境の設定
Anacondaの仮想環境に、Google Client Libraryをインストールする。これにより、Google APIやGoogle OAuthがPythonから使えるようになる。
まずAnaconda Promptで仮想環境に入る。
conda activate 環境名
Google Client Libraryを仮想環境にインストール。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
認証が通っているかの確認
公式リファレンスに記載の、quickstart.pyで認証が通るかを確認する。
下記のコードをquickstart.pyという名前で、先程作成したcredentials.jsonと同階層に保存し、実行。
https://developers.google.com/calendar/api/quickstart/python?hl=ja
from __future__ import print_function
import datetime
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
return
# Prints the start and name of the next 10 events
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
except HttpError as error:
print('An error occurred: %s' % error)
if __name__ == '__main__':
main()
実行は仮想環境下のAnaconda Promptで:
python quickstart.py
ブラウザが開くので、アプリの認証に使うユーザーを選択する。
直後に、「このアプリは確認されいません」という趣旨の警告が出る。「詳細」 > 「XXX(安全ではないページ)に移動」。
ブラウザに下記のように表示されたら認証に成功。
The authentication flow has completed. You may close this window.
認証に成功すると、credentials.jsonと同階層にtoken.jsonが作成される。以降、認証を通さなくてもAPIにアクセスできるようになる。