At the Forge - Databases and Calendars

Building with the iCalendar standard, it's time to extract schedule information from a database and build calendars on the fly.
Inserting New Data

Now that we have a defined table and indexes, we can start to populate our database table with some events. We can, as always, INSERT new events into our table with the following syntax:

  (event_summary, event_location,
   event_start, event_end)
  ('Ides of March', 'Everywhere',
 '2005-March-15 00:00', '2005-March-15 23:59:59')

As you can see, the above INSERT statement names only four of the six columns defined in Events. When we check our new row, we find the following:

atf=# select * from events;
-[ RECORD 1 ]---+---------------------------
event_id        | 1
event_summary   | Ides of March
event_location  | Everywhere
event_start     | 2005-03-15 00:00:00
event_end       | 2005-03-15 23:59:59
event_timestamp | 2005-04-04 01:20:15.575032

As you can see, event_id (which we defined to be of type SERIAL) has automatically received a value of 1. Furthermore, event_timestamp has been set with the date and time at which we executed the query.

It's easy to imagine how we could invoke this INSERT statement with a Web-based program using CGI or a more advanced system, such as mod_perl or Zope. Indeed, we really don't have to think much about how the data has arrived in the database, particularly if we have set appropriate constraints on our data. We can assume that whatever resides in the database is reliable, and that the server has rejected any entries that would violate our rules.

Creating a Dynamic iCalendar File

Now that we have some activities in our database table, we can retrieve them into a CGI program. That program then produces output in iCalendar format, allowing iCalendar clients to retrieve its data. Listing 1 contains the program, which is a modified version of last month's program. As I mentioned last month, I wrote this program in Python in no small part because of the relative dearth of modules to create iCalendar-format files. Fortunately, there is such a module for Python, and I have taken advantage of that fact in this program.

As you can see in Listing 1, the program is fairly straightforward. After importing a number of modules, we create a calendar object and insert the iCalendar-mandated fields indicating the source of the calendar.

We then connect to a PostgreSQL server, which is presumed to be on the local computer. Although several database adaptors exist in Python for PostgreSQL access, I have long used psycopg, which is both fast and stable. To connect to PostgreSQL with psycopg, we use the following syntax:

db_connection = psycopg.connect
                  ('dbname=atf user=reuven')

The above indicates that the database name is atf and the user name is reuven. You also might need to specify the server and a password as additional arguments, especially if you are working on a production system.

Once we have connected to the database, we get a cursor, which allows us to submit queries and get their results:

db_cursor = db_connection.cursor()

With a cursor in hand, we now can send our SQL query to the database, using Python's triple-quote functionality to make our SQL more readable. Now we retrieve our results. If we were expecting to retrieve dozens or hundreds of rows, we probably would want to get them one at a time, or perhaps in batches. But I know that this calendar will contain only a few events, so I use the fetchall() method to get them in one large sequence:

result_rows = db_crsor.fetchall()

Each element of result_rows is a row from our PostgreSQL database. We thus iterate (in a for loop) over the rows, retrieving the different elements that appear.

For the most part, this is pretty straightforward. However, things get a bit tricky when we are working with dates and times—important elements of any calendar of events! The problem is that psycopg uses the open-source mxDateTime module from, which makes working with dates extremely easy. But mxm's iCalendar module uses Python's datetime module, which is different. We thus need to retrieve each of the dates (for the event's starting time, ending time and stamp), turn them from an instance of mxDateTime into a datetime-compatible tuple, use that tuple to create an instance of datetime and then pass that to event.add, using the three calls starting with:

event.add('dtstart', datetime(tzinfo=UTC(),
event.add('dtend', datetime(tzinfo=UTC(),

The second argument to datetime() in the above three rows of code does exactly what we said. It retrieves one column from the returned row and turns it into a tuple. We then take a slice of the sequence (with Python's convenient [0:5] notation) to grab a subset of the items returned by tuple().

But we can't pass datetime() a sequence; rather, it is expecting a number of individual elements. In other words, datetime() wants several numbers, not a reference or pointer to a list of numbers. We turn the tuple into its individual elements with Python's * operator. Finally, sharp-eyed readers will notice that we have passed the tzinfo argument before the individual elements of the tuple; this is because Python requires that we pass named arguments before the * operator.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Problems with 'from iCalendar import UTC'

superbenk's picture

I don't see any class named 'UTC' in the iCalendar modules from Am I missing something?

Benjamin Krein