Google Calendar API - Access own calendar via Service account

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 00:27:04

I realized that 3-stepped OAuth works if one dumps the resulting credentials to JSON and reads them in every time you need them.

So the flow is: Add your client_secrets.json as stated on Google API in the same folder as this script. Grab the key from the url given in the prompt. Enter it on request to the prompt. Party!11. I hope these credentials last forever.

from oauth2client.client import flow_from_clientsecrets

flow = flow_from_clientsecrets('client_secrets.json',
                               scope='https://www.googleapis.com/auth/calendar',
                               redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()
print('Visit this site!')
print(auth_uri)
code = raw_input('Insert the given code!')
credentials = flow.step2_exchange(code)
print(credentials)

with open('credentials', 'wr') as f:
    f.write(credentials.to_json())

Now, in the application itself:

def __create_service():
    with open('credentials', 'rw') as f:
        credentials = Credentials.new_from_json(f.read())

    http = httplib2.Http()
    http = credentials.authorize(http)

    return build('calendar', 'v3', http=http)

To get a service object, one can now call

service = __create_service()

and use the API on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!