I’m trying to use google’s calendar API and I’m so lost. I figured out how to get authentication the first time around, when I send the user to approve the access scope, but I can’t figure out how to get the credentials I need to perform any other actions once the session for that original authorization goes away. Here is all my code around connection to google.
def connect_to_google(user_id):
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'])
flow.redirect_uri = 'https://tb-read.com/createcalendar'
authorization_url, state = flow.authorization_url(access_type="offline", include_granted_scopes="true", prompt="consent")
session['state'] = state
return redirect(authorization_url)```
@app.route('/createcalendar')
def create_calendar():
"""Create a new google calendar for the user"""
if not g.user:
flash ('Please log in', 'danger')
return redirect('/')
code = request.args.get('code')
state = session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'], state=state)
flow.redirect_uri = url_for('create_calendar', _external=True)
authorization_response = request.url
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
session['credentials'] = {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes
}
service = build('calendar', 'v3', credentials=credentials)
calendar = {
'summary': 'TB Read Calendar'
}
created_calendar = service.calendars().insert(body=calendar).execute()
user = db.session.execute(db.select(User).where(User.user_id == g.user.user_id)).scalar()
user.calendar_id = created_calendar['id']
user.google_code = code
db.session.add(user)
db.session.commit()
print('****************************')
print(user.calendar_id)
service.close()
return redirect(f'/users/{g.user.user_id}/calendar')
@app.route('/api/posting', methods=['POST'])
def schedule_posting_days():
"""Schedule a user's posting schedule on the google calendar"""
if not g.user:
flash ('Please log in', 'danger')
return redirect('/')
last_post_date = request.json['lastPostDate']
posting_frequency = request.json['postingFrequency']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'])
authorization_response = request.url
flow.fetch_token(authorization_response=authorization_response, code=g.user.google_code)
credentials = flow.credentials
session['credentials'] = {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes
}
service = build('calendar', 'v3', credentials=credentials)
## Check if a posting date event currently exists
existing_posting_event = db.session.execute(db.select(Event).where(Event.user_id == g.user.user_id).where(Event.eventcategory == 'Posting')).scalar()
## Delete remaining recurring posting events
if existing_posting_event.google_event_id:
post_event = service.events().get(calendarId=g.user.calendar_id, eventId = existing_posting_event.google_event_id).execute()
today = date.today()
post_event['recurrance'] = [f'RRULE: FREQ=DAILY; COUNT=g.user.posting_frequency; UNTIL={today}']
service.events().update(calendarId=g.user.calendar_id, EventId = existing_posting_event.google_event_id, body=post_event).execute()
## Add new posting date event
event = {
'summary': 'Posting Day',
'start.date': last_post_date,
'end.date': last_post_date,
'recurrence': [f'RRULE: FREQ=DAILY; COUNT={posting_frequency}']
}
posting_day = service.events().insert(calendarId = g.user.calendar_id, body=event).execute()
print('**************************')
print(posting_day)
service.close()
## Update user profile
if g.user.posting_frequency != posting_frequency:
user = db.session.execute(db.select(User).where(User.user_id == g.user.user_id)).scalar()
user.posting_frequency = posting_frequency
db.session.add(user)
db.session.commit()
return jsonify({'success': 'Posting Event Changed'})