Skip to content Skip to sidebar Skip to footer

Google Calendar Api - Access Own Calendar Via Service Account

I want to access the Google Calendar API to insert entries with Python. I created a Service account on the Google API console, added an private key, downloaded it. But when I try t

Solution 1:

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)

withopen('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.

Post a Comment for "Google Calendar Api - Access Own Calendar Via Service Account"