Monday, May 21, 2007

gspreadsheet python port

Ported the following into Python:
http://www.almaer.com/blog/archives/001382.html


import httplib, urllib,sys

# Auth
def auth(email, passwd):
params = urllib.urlencode({
'Email': email,
'Passwd': passwd,
'source': 'formula',
'service':'wise'}
)
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPSConnection("www.google.com")
conn.request("POST", "/accounts/ClientLogin", params, headers)
response = conn.getresponse()
data = ''.join(response.read())
conn.close()
import string
d=data.split('\n')
authinfo = ''
for dd in d:
auth = dd.split('=')
if auth[0] == 'Auth':
authinfo = auth[1]
break
if authinfo == '':
print 'error auth'
sys.exit(0)
return authinfo

# Set formula
def setformula(row, col, formula, authinfo, key):
XML = """<?xml version='1.0' ?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006">
<gs:cell row='""" + row + """' col='"""+ col + """' inputValue='="""+formula+ """' />
</entry>"""

resultpath = "/feeds/cells/"+key+"/1/private/full"
headers = {"Content-type": "application/atom+xml",
"Authorization": "GoogleLogin auth="+authinfo}
gsconn = httplib.HTTPConnection('spreadsheets.google.com')
gsconn.request("POST", resultpath, XML, headers)
result = gsconn.getresponse()
resultxml = ''.join(result.read())
gsconn.close()

# Get result
def getresult(row, col, authinfo, key):
resultpath = "/feeds/cells/" + key + "/1/private/basic/" + row + col
headers = {"Content-type": "application/atom+xml",
"Authorization": "GoogleLogin auth="+authinfo}
gsconn = httplib.HTTPConnection('spreadsheets.google.com')
gsconn.request("GET", resultpath, '', headers)
result = gsconn.getresponse()
resultxml = ''.join(result.read())
gsconn.close()

from xml.dom.minidom import parse,parseString
dom1 = parseString(resultxml)
elems = dom1.getElementsByTagName('content')
elem = elems[0]
return elem.firstChild.nodeValue


def getGF(key, email, passwd, formula):
authinfo = auth(email, passwd)
setformula('1', '1', formula, authinfo, key)
return getresult('A', '1', authinfo, key)

import sys, getopt

try:
opts, args = getopt.getopt(sys.argv[1:],
"k:u:p:f:h",
["key=","email=","password=","formula="])
for o, a in opts:
if o in ("-k", "--key"):
key = a
if o in ("-u", "--email"):
email = a
if o in ("-p", "--password"):
passwd = a
if o in ("-f", "--formula"):
formula = a
if o in ("-h", "--help"):
print "gf.py -k KEY -u EMAIL -p PASSWORD -f FORMULA"
sys.exit(0)
except getopt.error, msg:
print "getopt: "+ msg
sys.exit(0)

print getGF(key, email, passwd, formula)