Several years ago I created a small Python program which were able to maintain my calendar using oauth2client which is now deprecated and replaced with google.auth - but I cannot find any useful documentation and my program stopped working complaining about a _module KeyError which nobody appear to have solved except by upgrading.
I cannot figure out how to replace the oauth2client with google.auth:
import datetime
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
...
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
Authorize credentials for a desktop application If your app runs on multiple platforms, you must create a separate client ID for each platform. In the Google Cloud console, go to the Credentials page. Click Create Credentials > OAuth client ID. Click Application type > Desktop app.
According to the oauth2client deprecation notes, the replacement to be used to manage Google user credentials is google-auth-oauthlib. Below a snippet working on my PC (python 3.6).
As the documentation highlights the new library does not save the credentials, that's why I am using pickle to save them. Maybe, depending on your application requirements, you want to have a more robust solution (like a database).
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly', ]
# we check if the file to store the credentials exists
if not os.path.exists('credentials.dat'):
flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
credentials = flow.run_local_server()
with open('credentials.dat', 'wb') as credentials_dat:
pickle.dump(credentials, credentials_dat)
else:
with open('credentials.dat', 'rb') as credentials_dat:
credentials = pickle.load(credentials_dat)
if credentials.expired:
credentials.refresh(Request())
calendar_sdk = build('calendar', 'v3', credentials=credentials)
calendars_get_params = {
'calendarId': 'primary',
}
test = calendar_sdk.calendars().get(**calendars_get_params).execute()
print(test)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With