Using CGI to filter out iCal Events

Created: 2nd January 2020

My university uses iCal feeds to distribute timetables from the central university timetabling system. However, the feed contains lectures from all possible modules that I could be taking, rather than just those I take. This leaves my calendar cluttered and difficult to use.

Fortunately, the Computing Department provide web hosting from the public_html folder on our user account. This web hosting supports CGI (common gateway interface), a rather old way of implementing dynamic web sites. When a user makes a HTTP request to a CGI script, the web server doesn’t serve the script as static content. Instead it will execute the script with stdin being fed the HTTP request, and stdout being used to serve the HTTP response.

My makeshift solution to my calendar overload was to write a Python CGI script to filter out the unneeded calendar events. I added an iCal feed to my calendar with the URL corresponding to the CGI script. The script first downloads the latest version of my timetable from the actual iCal feed on the university system. It then uses the library icalendar to parse the iCal feed, and remove the unneeded events. This results in a new iCal feed which is sent back to my calendar app.

The relatively short Python code is presented below:

import icalendar, urllib.request, sys, re

    'CO337 Simulation and Modelling',
    'CO332 Advanced Computer Architecture',
    'CO Machine Learning Seminars',


regex = re.compile('^(' + '|'.join(FILTER_EVENTS_THAT_BEGIN_WITH) 
    + ')')
sys.stdout.buffer.write(b'Content-Type: text/calendar\n\n')
contents = urllib.request.urlopen(CALENDAR_URL).read()
cal = icalendar.Calendar.from_ical(contents)
cal.subcomponents = [component for component in cal.subcomponents 
    if not regex.match(component['SUMMARY'])]