2012-11-19

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(
        calendarId=calendarId,
        singleEvents=True,
        maxResults=1000,
        orderBy='startTime',
        timeMin='2012-11-01T00:00:00-08:00',
        timeMax='2012-11-30T00:00:00-08:00',
        pageToken=pageToken,
        ).execute()
    return events


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

if __name__ == '__main__':
    main()


--[ google_calendar.py

client_id='123456789012.apps.googleusercontent.com'
client_secret='aBcDeFgHiGkLMnOpQrStUvWx'
user_agent='xxxxxxxx/vXX'
developerKey='aBcDeFgHiGkLMnOpQrStUvWxYZ1234567890,.;'

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(
    client_id=client_id,
    client_secret=client_secret,
    scope='https://www.googleapis.com/auth/calendar',
    user_agent=user_agent)

# 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,
       developerKey=developerKey)
      

2012-11-09

Android CherryPy Cam

Android Twisted SpyCam:
http://kbcarte.wordpress.com/2011/08/31/android-twisted-spycam

Running CherryPy on Android:
http://www.defuze.org/archives/228-running-cherrypy-on-android-with-sl4a.html

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()
    im.close()
    os.remove(fn)
    return shot

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

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

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

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

if __name__ == '__main__':
    droid.wakeLockAcquireDim()
    run()