- Python hızlı başlangıç kılavuzu
- Hedefler
- Ön koşullar
- Ortamınızı ayarlayın
- API’yi etkinleştirme
- OAuth izin ekranını yapılandırma
- Masaüstü uygulaması için kimlik bilgilerini yetkilendirme
- Google istemci kitaplığını yükleme
- Örneği yapılandırın
- Örneği çalıştırın
- Sonraki adımlar
- Saved searches
- Use saved searches to filter your results more quickly
- balirampansare/google-calendar-api-python
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- How to get started with Google Calendar API using Python with Examples
- 1. How to Create a project in Google Developer Console?
- 2. Set up the Google API Service
- 2. How to Fetch list of all Calendars from a User Account using Calendar API
Python hızlı başlangıç kılavuzu
Hızlı başlangıç kılavuzları, Google Workspace API’si çağıran bir uygulamanın nasıl ayarlanıp çalıştırılacağını açıklar.
Google Workspace hızlı başlangıç kılavuzları, kimlik doğrulama ve yetkilendirme akışının bazı ayrıntılarını işlemek için API istemci kitaplıklarını kullanır. İstemci kitaplıklarını kendi uygulamalarınızda kullanmanızı öneririz. Bu hızlı başlangıç kılavuzu, test ortamı için uygun olan basitleştirilmiş bir kimlik doğrulama yaklaşımı kullanır. Üretim ortamında, uygulamanız için uygun olan erişim kimlik bilgilerini seçmeden önce kimlik doğrulama ve yetkilendirme hakkında bilgi edinmenizi öneririz.
Google Calendar API’ye istekte bulunan bir Python komut satırı uygulaması oluşturun.
Hedefler
- Ortamınızı ayarlayın.
- İstemci kitaplığını yükleyin.
- Örneği oluşturun.
- Örneği çalıştırın.
Ön koşullar
Bu hızlı başlangıç kılavuzunu çalıştırmak için aşağıdaki önkoşullara ihtiyacınız vardır:
Ortamınızı ayarlayın
Bu hızlı başlangıç kılavuzunu tamamlamak için ortamınızı kurun.
API’yi etkinleştirme
OAuth izin ekranını yapılandırma
Bu hızlı başlangıç kılavuzunu tamamlamak için yeni bir Google Cloud projesi kullanıyorsanız OAuth izin ekranını yapılandırın ve kendinizi test kullanıcısı olarak ekleyin. Cloud projeniz için bu adımı zaten tamamladıysanız sonraki bölüme geçin.
- Google Cloud Console’da Menü menu >API’ler ve Hizmetler >OAuth izin ekranı‘na gidin. OAuth izin ekranına git
- Uygulamanızın kullanıcı türünü seçin, ardından Oluştur‘u tıklayın.
- Uygulama kayıt formunu doldurup Kaydet ve Devam Et‘i tıklayın.
- Şu an için kapsam eklemeyi atlayıp Kaydet ve Devam Et‘i tıklayabilirsiniz. İleride, Google Workspace kuruluşunuz dışında kullanılacak bir uygulama oluşturduğunuzda, uygulamanızın gerektirdiği yetkilendirme kapsamlarını eklemeniz ve doğrulamanız gerekir.
- Kullanıcı türü olarak Harici‘yi seçtiyseniz test kullanıcıları ekleyin:
- Test kullanıcıları bölümünde Kullanıcı ekle‘yi tıklayın.
- E-posta adresinizi ve diğer yetkili test kullanıcılarını girip Kaydet ve Devam Et‘i tıklayın.
Masaüstü uygulaması için kimlik bilgilerini yetkilendirme
- Google Cloud Console’da Menü menu >API’ler ve Hizmetler >Kimlik Bilgileri‘ne gidin. Kimlik Bilgileri’ne git
- Kimlik bilgisi oluştur >OAuth istemci kimliği‘ni tıklayın.
- Uygulama türü >Masaüstü uygulaması‘nı tıklayın.
- Ad alanına, kimlik bilgisi için bir ad yazın. Bu ad yalnızca Google Cloud Console’da gösterilir.
- Oluştur‘u tıklayın. Yeni istemci kimliğinizi ve istemci gizli anahtarınızı gösteren OAuth istemcisi tarafından oluşturulan ekran görünür.
- OK (Tamam) seçeneğini tıklayın. Yeni oluşturulan kimlik bilgisi OAuth 2.0 istemci kimlikleri altında görünür.
- İndirilen JSON dosyasını credentials.json olarak kaydedin ve çalışma dizininize taşıyın.
Google istemci kitaplığını yükleme
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Örneği yapılandırın
- Çalışma dizininizde, quickstart.py adlı bir dosya oluşturun.
- quickstart.py alanına aşağıdaki kodu ekleyin:
from __future__ import print_function import datetime import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] def main(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. 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 the next run with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('calendar', 'v3', credentials=creds) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 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 found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except HttpError as error: print('An error occurred: %s' % error) if __name__ == '__main__': main()
Örneği çalıştırın
- Google Hesabınızda oturum açmadıysanız oturum açmanız istenir. Birden çok hesapta oturum açtıysanız yetkilendirme için kullanılacak bir hesap seçin.
- Kabul et‘i tıklayın.
Yetkilendirme bilgileri dosya sisteminde depolanır. Böylece, örnek kodu bir sonraki çalıştırmanızda yetkilendirme istenmez.
Google Calendar API’ye istek gönderen ilk Python uygulamanızı başarıyla oluşturdunuz.
Sonraki adımlar
Aksi belirtilmediği sürece bu sayfanın içeriği Creative Commons Atıf 4.0 Lisansı altında ve kod örnekleri Apache 2.0 Lisansı altında lisanslanmıştır. Ayrıntılı bilgi için Google Developers Site Politikaları’na göz atın. Java, Oracle ve/veya satış ortaklarının tescilli ticari markasıdır.
Son güncelleme tarihi: 2023-07-12 UTC.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Create, Update, Delete calendars and events using google calendar API in python
balirampansare/google-calendar-api-python
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Google Calendar API Using Python
Want to integrate google calendar api in your application? Link
At the end you will know how to create, update, delete the calendars and events.
- Create Google Cloud Platform project with the google calendar API enabled and download the client json file by creating OAuth Credentials. (googleconsolecloudlink)
- Save the client json file in your working directory.
- A Google account with Google Calendar enabled.
Step 1: Install the Google client library
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Step 2: Configure the sample
- In your working directory, create a file name google.py file.
- To include code in it check out the repo above or the link (configure the sample)
Step 3: Creating service to create google calendar api
- While creating service you need to add scope.
- scope — Access that should be given to the user (link)
- In our project we are giving read, write action to the user
Step 4: Create,Update,Delete Calendar
#Supplying the required calendar info in request_body request_body = < 'summary': 'calendarSummary', #Calendar Title 'timeZone': 'Asia/Kolkata' >#returning the request_body in response response = service.calendars().insert(body=request_body).execute()
#retrieve the calendar you want to update # here i retrieved the required calendar as myCalendar myCalendar['summary'] = 'new summary' myCalendar['description'] = 'new description' service.calendars().update(calendarId = myCalendar['id'],body =myCalendar).execute() #check out calendar_update.py file for better explanation.
service.calendars().delete(calendarId='id_of_calendar_to_delete').execute()
Step 5: Create, Update, Delete Event
Below is the code of the project, you can add more body request for event. Create event
#id of the project calendar_id_proj = '. ' #----------request body of event-----------# event_request_body = < 'start':< 'dateTime': convert_to_RFC_datetime(2022,2,13,2 ), #(yyyy,mm,dd,time) 'timeZone' : 'Asia/Kolkata' >, 'end':< 'dateTime': convert_to_RFC_datetime(2022,2,13,3), 'timeZone' : 'Asia/Kolkata' >, 'summary': 'MLProj Meet', 'description':'discussion of the final yr project', 'colorId': 5, 'Status': 'confirmed', 'transparency':'opaque', 'visibility':'private', 'location':'Thane, Viviana', 'attendees':[ < 'displayName' : 'Tom', 'comment' : 'cool guy', 'email' : 'tp@example.com', 'optional': False, #optional: means whether this attendee is optional or not 'organizer': True, 'responseStatus': 'accepted' >] > maxAttendees = 5 sendNotification = True sendUpdates = 'none' #-----------Creating Event------------# response = service.events().insert( calendarId = calendar_id_proj, maxAttendees =maxAttendees, sendNotifications=sendNotification, sendUpdates=sendUpdates, body=event_request_body, ).execute()
calendar_id = '. ' eventId = '. ' # First retrieve the event from the API. event = service.events().get(calendarId=calendar_id, eventId=EventId).execute() event['summary'] = 'Project Meet' . . updated_event = service.events().update(calendarId=calendar_id, eventId=EventId, body=event).execute()
calendar_id = '. ' EventId = '. ' service.events().delete(calendarId=calendar_id, eventId=EventId).execute()
About
Create, Update, Delete calendars and events using google calendar API in python
How to get started with Google Calendar API using Python with Examples
Google Calendar offers one of the most convenient and popular ways to manage schedule,
events, meetings, or even plan out your holiday events. A few things you think will
be straightforward end up being complicated for customised need. The Google Calendar
API lets you automate your calendar, for those custom needs.1. How to Create a project in Google Developer Console?
To kick things off lets head Google Developers Console and create a new project.
We name the project as Automating Calendar, further to it, get the credentials.2. Set up the Google API Service
import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/calendar'] CREDENTIALS_FILE = 'credentials.json' def get_calendar_service(): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. 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_FILE, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('calendar', 'v3', credentials=creds) return service
2. How to Fetch list of all Calendars from a User Account using Calendar API
Let us create a file with name list_calendars.py in the same directory as that of cal_setup.py with the snippet below:
from cal_setup import get_calendar_service def main(): service = get_calendar_service() # Call the Calendar API print('Getting list of calendars') calendars_result = service.calendarList().list().execute() calendars = calendars_result.get('items', []) if not calendars: print('No calendars found.') for calendar in calendars: summary = calendar['summary'] primary = "Primary" if calendar.get('primary') else "" print("%s\t%s\t%s" % (summary, id, primary)) if __name__ == '__main__': main()
The above code is calling the Calendar API with the credentials that have already been setup, it will fetch all the calendars. When the above code is run for the first time, a google auth link will be opened in default browser seeking permission to access the calendar, after the consent is provided a token is saved which can be used for making requests in future to the Google Calendar API. Once the code has run, in the terminal you will see on the console the names of all the calendars that you have created. If you want to do more things, we have created an in-depth article with screenshots — how to automate google calendar with python The entire source code can be found here on our github.