I am working with the Google Calendar API, but my Oauth2.0 token expires every week and requires manual re-authorization through a web browser with my Google account. Is there a method to automate this authorization renewal process on a weekly basis?
from __future__ import print_function
import datetime
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# Define the scopes needed for calendar access
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def main():
"""
Demonstrates basic usage of the Google Calendar API.
Outputs the start and title of the next 10 events from the user's calendar.
"""
creds = None
# Check if the token file exists
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If credentials are not valid, prompt user for login
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 next time
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('calendar', 'v3', credentials=creds)
# Fetch upcoming events from the calendar
now = datetime.datetime.utcnow().isoformat() + 'Z' # Z indicates UTC time
print('Retrieving the next 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 available.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
if __name__ == '__main__':
main()