파이썬

python 에서 구글 캘린더 api 이용하기(server to server)

by nanumi posted Sep 17, 2021
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

 

datetime zone에서의 오류메시지

Details: "[{'domain': 'global', 'reason': 'badRequest', 'message': 'Bad Request'}]">

'dateTime': '2020-10-31T17:00:00.000',
'timeZone': 'GMT-03:00'

 

날짜 시간 값은 UTC "TZ" 형식이어야 합니다. 거의 모든 CRM 및 공개 API는 이 형식의 시간을 허용합니다. 주요 언어(예: C 또는 Java) 라이브러리 함수/메서드를 사용하여 날짜/시간을 UTC 시간으로 변환하면 YYYY-MM-DDTHH:MM:SS.MMMZ 형식의 날짜/시간 인스턴스를 반환합니다.

 

요컨대, timeMin및 timeMax변수 모두에서 표준 시간대 오프셋이 누락되었습니다 timeZone이는 변수를 설정한 경우에도 필요합니다 .

예를 들어, 저는 America/New_York 시간대에 살고 있으므로 오프셋은 -05:00, 현재 가지고 있는 값에 추가해야 합니다. 그래서 저에게 값은 다음과 같을 것입니다.

{
    ...
    "timeMin": "2012-01-31T09:00:00-05:00",
    "timeMax": "2012-01-31T10:00:00-05:00",
    ...
}

더 구체적를하기 위해, 구글 캘린더 API가 요구하는 timeMintimeMax

필수 시간대 오프셋 이 있는 RFC3339 타임스탬프여야 합니다( 예: 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z). 밀리초가 제공될 수 있지만 무시됩니다. timeMax가 설정되면 timeMin은 timeMax보다 작아야 합니다.

따라서 2012-01-31T09:00:00-5:00또는 2012-01-31T09:00:00Z밀리초를 선택 사항으로 가질 수 있습니다 (어쨌든 무시되기 때문에).

Google 캘린더 이벤트 목록 API의 난에서 모든 정보를 어디서 얻었 문서입니다.


 

 

 

 

 

아래의 사이트에서 구글캘린더 api 설정을 다했으면 코딩소스를 실행하면 됩니다.

https://console.cloud.google.com/home/dashboard?project=calen-326223

 

 

처음실행시 인증절차를 거치게되며,

 

https://accounts.google.com/o/oauth2/auth?client_id=49866703108-89bnmpum5lk13v8juc3u2v5cb0c6g7ff.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&access_type=offline&response_type=code

 

화면에 나오는대로 클릭을 하다보면 성공입니다.

 

 

GMT_OFF = '+09:00' 

 +09:00 이면 KOREA, JAPAN 시간을 말한다.

 

#https://www.py4u.net/discuss/273522

from __future__ import print_function  ## 이 라인은 최상단에 위치해야 오류가 발생하지 않는다함.

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2 import service_account
from httplib2 import Http
from oauth2client import file, client, tools

scopes = ['https://www.googleapis.com/auth/calendar']

try:
    import argparse
    flags = argparse.ArgumentParser(parents=
[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/calendar'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('./구글캘린더JSON.json',
SCOPES)
    creds = tools.run_flow(flow, store, flags) \
          if flags else tools.run(flow, store)
CAL = build('calendar', 'v3', http=creds.authorize(Http()))

GMT_OFF = '+09:00'          # ET/MST/GMT-4
EVENT1 = {
    'summary': '양산이트레이더스',
    'start': {'dateTime': '2021-09-20T11:00:00%s' % GMT_OFF},
    'end': {'dateTime': '2021-09-20T12:00:00%s' % GMT_OFF},
}
EVENT2 = {
    'summary': '장모님납골당',
    'start': {'dateTime': '2021-09-20T08:00:00%s' % GMT_OFF},
    'end': {'dateTime': '2021-09-20T09:00:00%s' % GMT_OFF},
}
EVENT3 = {
    'summary': '집에와서 운동하기',
    'start': {'dateTime': '2021-09-20T19:00:00%s' % GMT_OFF},
    'end': {'dateTime': '2021-09-20T20:00:00%s' % GMT_OFF},
}

e = CAL.events().insert(calendarId='primary',
                sendNotifications=True, body=EVENT1).execute()
e = CAL.events().insert(calendarId='primary',
                sendNotifications=True, body=EVENT2).execute()
e = CAL.events().insert(calendarId='primary',
                sendNotifications=True, body=EVENT3).execute()

 

python 에서 구글 캘린더 api 이용하기(server to server)

아래 문서를 참고하면 된다.

  1. Python Quickstart  : 여기 내용에서 get_credentials() 만 좀 달라진다.
  2. Using OAuth 2.0 for Server to Server Applications | API Client Library for Python | Google Developers

 

순서

  1. 구글 캘린더에 대한 service account 를 생성한다. 이것은 여기를 참고하자.
  2. Google client library 를 설치한다.
  3. 예제를 setup
  4. 예제를 실행

 

구글 캘린더에 대한 service account 를 생성 

구글 캘린더 연동 방법 > 자신의 calendar 에 접근해서 data를 가져오는 경우를 참고하자.
 

Google client library 를 설치

설치는 간단하다. pip install 을 해주면 된다.

pip install --upgrade google-api-python-client

 

예제

예제는 여기서 확인할 수 있다. 일단 credential 까지만 되는 것을 확인하자.
 

from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/calendar']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'server_account.json', scopes)


from httplib2 import Http
http_auth = credentials.authorize(Http())


from apiclient.discovery import build
service = build('calendar', 'v3', http=http_auth)



 

그 이후 동작들

이제 calendar 관련 다른 api 를 다루는 것은 아래 문서를 참고하면 된다.

 

Date-Times Reccurence 관련 specification

 


Articles

1 2 3 4 5