Google Calendar API: Insert multiple events (in Python)

2024/10/11 22:25:02

I am using the Google Calendar API, and have successfully managed to insert a single event into an authorized primary calendar, but I would like to hard code multiple events that, when executed, would populate the users calendar.

For example:

  • June 24th 1:00pm "Buy apples"
  • June 26th 3:00pm "Pick up clothes"
  • August 21st 1:00pm "Clean car"
  • September 1st 2:00pm "Return books"

My code right now is:

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, toolstry:import argparseflags = argparse.ArgumentParser(parents=
[tools.argparser]).parse_args()
except ImportError:flags = NoneSCOPES = 'https://www.googleapis.com/auth/calendar'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:flow = client.flow_from_clientsecrets('client_secret.json', 
SCOPES)creds = tools.run_flow(flow, store, flags) \if flags else tools.run(flow, store)
CAL = build('calendar', 'v3', http=creds.authorize(Http()))GMT_OFF = '-04:00'          # ET/MST/GMT-4
EVENT = {'summary': 'Buy apples','start': {'dateTime': '2017-06-24T13:00:00%s' % GMT_OFF},'end': {'dateTime': '2017-06-24T14:00:00%s' % GMT_OFF},
}e = CAL.events().insert(calendarId='primary',sendNotifications=True, body=EVENT).execute()print('''*** %r event added:Start: %sEnd: %s''' % (e['summary'].encode('utf-8'),e['start']['dateTime'], e['end']['dateTime']))

I need to know how to add the remaining events, as an example, to the calendar at the same time. Multiple non-recurring events within one Google Calendar event insert.

Answer

Unfortunately events can only be executed one event at a time, which means the events.insert() method must be called multiple times. To hard code several events you need to recall

    e = CAL.events().insert(calendarId='primary',sendNotifications=True, body=EVENT).execute()

with a different "body" parameter set.

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, toolstry:import argparseflags = argparse.ArgumentParser(parents=
[tools.argparser]).parse_args()
except ImportError:flags = NoneSCOPES = 'https://www.googleapis.com/auth/calendar'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:flow = client.flow_from_clientsecrets('client_secret.json',
SCOPES)creds = tools.run_flow(flow, store, flags) \if flags else tools.run(flow, store)
CAL = build('calendar', 'v3', http=creds.authorize(Http()))GMT_OFF = '-04:00'          # ET/MST/GMT-4
EVENT1 = {'summary': 'Buy apples','start': {'dateTime': '2017-06-24T13:00:00%s' % GMT_OFF},'end': {'dateTime': '2017-06-24T14:00:00%s' % GMT_OFF},
}
EVENT2 = {'summary': 'Buy Bannanas','start': {'dateTime': '2017-06-25T13:00:00%s' % GMT_OFF},'end': {'dateTime': '2017-06-25T14:00:00%s' % GMT_OFF},
}
EVENT3 = {'summary': 'Buy candy','start': {'dateTime': '2017-06-26T13:00:00%s' % GMT_OFF},'end': {'dateTime': '2017-06-26T14:00:00%s' % GMT_OFF},
}e = CAL.events().insert(calendarId='primary',sendNotifications=True, body=EVENT1).execute()
e = CAL.events().insert(calendarId='primary',sendNotifications=True, body=EVENT2).execute()
e = CAL.events().insert(calendarId='primary',sendNotifications=True, body=EVENT3).execute()

The google calendar "body" parameter takes in specifically a single event and will thrown a 400 HTTP error with an array of events passed in

https://en.xdnf.cn/q/118267.html

Related Q&A

Remove special characters from column headers

I have a dictionary (data_final) of dataframes (health, education, economy,...). The dataframes contain data from one xlsx file. In one of the dataframes (economy), the column names have brackets and s…

Python Flask application getting OPTIONS instead of POST

I have a python Flask listener waiting on port 8080. I expect another process to make a series of POSTs to this port.The code for listener is as follows.#!/usr/bin/env python2 from __future__ import pr…

Raspberry pi:convert fisheye image to normal image using python

I have attached the USB webcam with raspberry pi to capture image and write code to send it using mail. It captures image using fswebcam commamnd so code for capture image in python script is :subproce…

modifying python daemon script, stop does not return OK (but does kill the process)

Following on from the previous post, the script now start and stops the python script (and only that particular script) correctly but does not report the OK back to the screen...USER="root" A…

fulfill an empty dataframe with common index values from another Daframe

I have a daframe with a series of period 1 month and frequency one second.The problem the time step between records is not always 1 second.time c1 c2 2013-01-01 00:00:01 5 3 2013-01-0…

How to mix numpy slices to list of indices?

I have a numpy.array, called grid, with shape:grid.shape = [N, M_1, M_2, ..., M_N]The values of N, M_1, M_2, ..., M_N are known only after initialization.For this example, lets say N=3 and M_1 = 20, M_…

Visualize strengths and weaknesses of a sample from pre-trained model

Lets say Im trying to predict an apartment price. So, I have a lot of labeled data, where on each apartment I have features that could affect the price like:city street floor year built socioeconomic s…

Scrapy get result in shell but not in script

one topic again ^^ Based on recommendations here, Ive implemented my bot the following and tested it all in shell :name_list = response.css("h2.label.title::text").extract()packaging_list = r…

How to find a source when a website uses javascript

What I want to achieve I am trying to scrape the website below using Beautiful-soup and when I load the page it does not give the table that shows various quotes. In my previous posts folks have helped…

How to print a list of dicts as an aligned table?

So after going through multiple questions regarding the alignment using format specifiers I still cant figure out why the numerical data gets printed to stdout in a wavy fashion.def create_data(soup_ob…