By exploring many different approaches, I learned that authentication between servers is what I wanted. Thus, the user does not have to explicitly grant permissions, and purchased auth-tokens do not need to be updated. Instead, using the service account, the server can make calls on its own.
Before you can start coding, you need to set up such a service account and add it to your calendar, to which you want to access the service account. Google recorded three steps to create an account here . Then go to https://calendar.google.com , find on the left side of the screen the calendar that you want to share with the new service account, and click the triangle next to it. Select your calendar settings from the drop-down menu. This will take you to a screen where you will find the calendar identifier that you will need later (to record it), and also displays a tab at the top to provide access to the calendar. As a "person", insert the email address from the service account, give it the appropriate permissions and click "Save" (if you do not click the "Save service account" button, it will not be added).
The code for this is actually quite elegant:
import os from datetime import timedelta import datetime import pytz import httplib2 from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials service_account_email = ' XXX@YYY.iam.gserviceaccount.com ' CLIENT_SECRET_FILE = 'creds.p12' SCOPES = 'https://www.googleapis.com/auth/calendar' scopes = [SCOPES] def build_service(): credentials = ServiceAccountCredentials.from_p12_keyfile( service_account_email=service_account_email, filename=CLIENT_SECRET_FILE, scopes=SCOPES ) http = credentials.authorize(httplib2.Http()) service = build('calendar', 'v3', http=http) return service def create_event(): service = build_service() start_datetime = datetime.datetime.now(tz=pytz.utc) event = service.events().insert(calendarId='<YOUR EMAIL HERE>@gmail.com', body={ 'summary': 'Foo', 'description': 'Bar', 'start': {'dateTime': start_datetime.isoformat()}, 'end': {'dateTime': (start_datetime + timedelta(minutes=15)).isoformat()}, }).execute() print(event)
I am using oauth2client version 2.2.0 ( pip install oauth2client ).
Hope this answer helps :)
source share