Last active
July 8, 2022 14:37
-
-
Save nelsondev19/7b29221e635588d0b267ce7946d945c9 to your computer and use it in GitHub Desktop.
Google Calendar API con Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from os import path | |
import pickle | |
from google.auth.transport.requests import Request | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from googleapiclient.discovery import build | |
# IF YOU MODIFY THE SCOPE DELETE THE TOKEN.TXT FILE | |
SCOPES = ['https://www.googleapis.com/auth/calendar.events', | |
'https://www.googleapis.com/auth/calendar'] | |
# THE TOKEN.TXT FILE STORES UPDATE AND USER ACCESS TOKENS | |
def get_crendetials_google(): | |
# OPEN THE BROWSER TO AUTHORIZE | |
flow = InstalledAppFlow.from_client_secrets_file("creds.json", SCOPES) | |
creds = flow.run_local_server(port=0) | |
# WE SAVE THE CREDENTIALS | |
pickle.dump(creds, open("token.txt", "wb")) | |
return creds | |
# THIS ALLOWS US TO INTERACT WITH ALL GOOGLE APIS, IN THIS CASE CALENDAR | |
def get_calendar_service(): | |
creds = None | |
if path.exists("token.txt"): | |
creds = pickle.load(open("token.txt", "rb")) | |
# IF IT EXPIRED, WE REFRESH THE CREDENTIALS | |
if not creds or not creds.valid: | |
if creds and creds.expired and creds.refresh_token: | |
creds.refresh(Request()) | |
else: | |
creds = get_crendetials_google() | |
service = build("calendar", "v3", credentials=creds) | |
return service | |
# METHODS | |
service = get_calendar_service() | |
# CREATE EVENT | |
def create_event(template: dict): | |
try: | |
response = service.events().insert(calendarId="primary", body=template).execute() | |
return response | |
except Exception as e: | |
return e.message | |
# GET EVENT BY ID | |
def get_event(eventId: str): | |
try: | |
response = service.events().get(calendarId="primary", eventId=eventId).execute() | |
return response | |
except Exception as e: | |
return e.message | |
# UPDATE EVENT | |
def update_event(eventId: str, template: dict): | |
try: | |
response = service.events().update(calendarId='primary', | |
eventId=eventId, body=template).execute() | |
return response | |
except Exception as e: | |
return e.message | |
# DELETE EVENT BY ID | |
def delete_event(eventId: str): | |
try: | |
response = service.events().delete(calendarId="primary", eventId=eventId).execute() | |
return response | |
except Exception as e: | |
return e.message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dependencies
Credentials of Google Cloud in JSON
Template