Retrieving Google Calendar Events with Python

I was looking for sample code to retrieve a set of events from Google Calendar via the google-api-python-client v3.  The information is scattered around different places.  Below I put everything together to remind my future self how to do it.

Note that the first time you run it, you will have to manually authorize the initial oauth credential through a web browser.

You can install google-api-python-client by:
sudo pip install google-api-python-client

man.py - test code
google_calendar.py - sample code provided by Google 
--[ main.py

calendarId = 'user@example.com'

import google_calendar
import pprint

def getEvents(pageToken=None):
    events = google_calendar.service.events().list(
    return events

def main():
    events = getEvents()
    while True:
        for event in events['items']:
        page_token = events.get('nextPageToken')
        if page_token:
            events = getEvents(page_token)

if __name__ == '__main__':

--[ google_calendar.py


import os.path
here = os.path.dirname(os.path.realpath(__file__))
storage_file = os.path.join(here, 'calendar.dat')

import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret are copied from the API Access tab on
# the Google APIs Console
FLOW = OAuth2WebServerFlow(

# To disable the local server feature, uncomment the following line:
FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage(storage_file)
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)

# Build a service object for interacting with the API. Visit
# the Google APIs Console
# to get a developerKey for your own application.
service = build(serviceName='calendar', version='v3', http=http,


Android CherryPy Cam

Android Twisted SpyCam:

Running CherryPy on Android:

Combining the two to run a CherryPy app on Android, which allow you to take a snapshot remotely by visiting http://x.x.x.x:8080 from a browser in the same LAN segment.

It needs to acquire at least a dim wakelock, otherwise it won't work after android goes to sleep.  Have to kill the app to release the wakelock though.

# -*- coding: utf-8 -*-

# Visit <phone_IP>:8080 to take a snapshot
# and display the snapshot in the web page.
# dkf 121104 creation

# The multiprocessing package isn't
# part of the ASE installation so
# we must disable multiprocessing logging
import logging
logging.logMultiprocessing = 0

import os.path

import android
import cherrypy

droid = android.Android()
here = os.path.abspath(os.path.dirname(__file__))

def snap():
    fn = os.path.join(here, 'latest.jpg')
    droid.cameraCapturePicture(fn, True)
    im = open(fn, 'rb')
    shot = im.read()
    return shot

class Root(object):
    def __init__(self):
        self.droid = android.Android()

    def index(self):
        return "<a href='snapshot'>Click here to take snapshot</a>"

    def snapshot(self):
        cherrypy.response.headers['content-type'] = 'image/jpeg'
        return snap()

def run():
    cherrypy.config.update({'server.socket_host': ''})
    cherrypy.quickstart(Root(), '/')

if __name__ == '__main__':


Swapping text segments in Vim

I have a text file with a lot of lines like these:

somebody@abc.com,someoneelse@xyz.com (Invoice 10001234) Recipient Refused
john@company.ca (Invoice 10001235) Recipient Refused
manager@firm.com (Invoice 10001235)

which I would like to turn into lines like these:

(Invoice 10001234) somebody@abc.com,someoneelse@xyz.com  Recipient Refused
(Invoice 10001235) john@company.ca  Recipient Refused
(Invoice 10001235) manager@firm.com

It can be done in Vim with the following command:

:%s#\(.*\)\((Invoice [^)]*)\)\(.*\)#\2 \1\3#


:   command mode
%s  substitute in whole file
#   separator

\(.*\)                1st grouping
\((Invoice [^)]*)\)   2nd grouping
\(.*\)                3rd grouping

In 2nd grouping,
[^)]*  match as many characters as possible as long as it is not )

\1  back reference to 1st grouping

\2  back reference to 2nd grouping
\3  back reference to 3rd grouping

Vim is powerful!


Getting LAN IP address of local computer

Using Python to get the LAN IP address of the local computer:

If we use:

import socket

we will get '' which may not be what we want due to the presence of the hosts file.

We could use:

import socket

we will get something like '192.168.0.xxx' which is more likely what we want.

The above code fragment works in Windows XP, may need adjustment in getting the host name in other OS.


Install Apache 2.2 in Fedora 15

I would like to install Apache (2.2) in Fedora 15, and found this post useful.  In short, these are the steps:
  1. sudo yum install httpd
  2. sudo chkconfig httpd on (run on startup)
  3. /etc/init.d/httpd start (start service now)
  4. netstat -tulpn | grep :80 (verify)
The netstat flags are:

-t tcp
-u udp
-l listening
-p program
-n numeric

And the Apache config file is here: