My favorites | Sign in
Project Logo
                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/python
"""
Python wrapper for Google Spreadsheets

http://code.google.com/p/pygspreadsheets/
"""

import urllib
import urllib2
import httplib
import datetime
import time
import os.path
import xml.dom.minidom
from xml.dom import minidom
from urlparse import urlparse

class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
return result
def http_error_201(self,req,fp,code,msg,headers):
print "this is OOOK"
return 1
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
gsessionid = headers.dict['location'].split('?')[1].split('=')[1]
return gsessionid



class gSpreadsheet:
global gsessionid
worksheets = {}
sid = ""
lsid = ""
auth = ""
gses=""

def getAuth(self,email,password):
url = "https://www.google.com/accounts/ClientLogin?Email=%s&Passwd=%s&source=pamela-fox-ss&service=wise" % (email, password)
data = urllib2.urlopen(url).read().split('\n')
self.sid = data[0].split('=')[1]
self.lsid = data[1].split('=')[1]
self.auth = data[2].split('=')[1]
print "Authorized"

def getSpreadsheetsList(self):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = "http://spreadsheets.google.com/feeds/spreadsheets/private/full"
headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl)
req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
data = data.read()
dom = xml.dom.minidom.parseString(data)

entries=dom.getElementsByTagName('entry')
spreadsheets = []

for entry in entries:
dentry={}
dentry['id']=entry.getElementsByTagName('id')[0].firstChild.data
dentry['updated']=entry.getElementsByTagName('updated')[0].firstChild.data
dentry['title']=entry.getElementsByTagName('title')[0].firstChild.data
try: dentry['content']=entry.getElementsByTagName('content')[0].firstChild.data
except AttributeError: dentry['content']=''
dentry['linkFeedHref']=entry.getElementsByTagName('link')[0].getAttribute('href')
dentry['authorName']=entry.getElementsByTagName('author')[0].getElementsByTagName('name')[0].firstChild.data
dentry['authorEmail']=entry.getElementsByTagName('author')[0].getElementsByTagName('email')[0].firstChild.data

spreadsheets.append(dentry)

return spreadsheets

except urllib2.URLError, e:
print "Request: " + req
print "Error: " + e.read()


def getWorksheets(self, linkFeedHref):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = linkFeedHref

headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl)
req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
data = data.read()
dom = xml.dom.minidom.parseString(data)

entries=dom.getElementsByTagName('entry')
worksheets = []
for entry in entries:
dentry={}
dentry['id']=entry.getElementsByTagName('id')[0].firstChild.data
dentry['updated']=entry.getElementsByTagName('updated')[0].firstChild.data
dentry['title']=entry.getElementsByTagName('title')[0].firstChild.data
dentry['listFeedHref']=entry.getElementsByTagName('link')[0].getAttribute('href')
dentry['cellsFeedHref']=entry.getElementsByTagName('link')[1].getAttribute('href')
dentry['colCount']=entry.getElementsByTagName('gs:colCount')[0].firstChild.data
dentry['rowCount']=entry.getElementsByTagName('gs:rowCount')[0].firstChild.data
worksheets.append(dentry)

# print worksheets
return worksheets

except urllib2.URLError, e:
print "Request: " + req
print "Error: " + e.read()



def getWorksheetListFeed(self,listFeedHref,query='',projection='full'):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = listFeedHref.replace('full',projection)
if(query != ''):
authurl = authurl + '?sq=' + urllib.quote(query)

headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl)
req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
data = data.read()
dom = xml.dom.minidom.parseString(data)
entries=dom.getElementsByTagName('entry')
rows = []
for entry in entries:
dentry={}
for child in entry.childNodes:

try: dentry[child.nodeName]=entry.getElementsByTagName(child.nodeName)[0].firstChild.data
except AttributeError: dentry[child.nodeName]=''
rows.append(dentry)

return rows

except urllib2.URLError, e:
print req
print "Error: " + e.read()


def getWorksheetCellsFeed(self,cellsFeedHref,query=''):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = cellsFeedHref
if(query != ''):
authurl = authurl + '?' + urllib.quote(query)

headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl)
req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
data = data.read()

dom = xml.dom.minidom.parseString(data)

entries=dom.getElementsByTagName('entry')
rows = []
for entry in entries:
dentry={}
for child in entry.childNodes:
try: dentry[child.nodeName]=entry.getElementsByTagName(child.nodeName)[0].firstChild.data
except AttributeError: dentry[child.nodeName]=''
dentry['row'] = entry.getElementsByTagName('gs:cell')[0].getAttribute('row')
dentry['col'] = entry.getElementsByTagName('gs:cell')[0].getAttribute('col')
dentry['selfHref'] = entry.getElementsByTagName('link')[0].getAttribute('href')
dentry['editHref'] = entry.getElementsByTagName('link')[1].getAttribute('href')
dentry['inputVal'] = entry.getElementsByTagName('gs:cell')[0].getAttribute('inputValue')
rows.append(dentry)

return rows

except urllib2.URLError, e:
print req
print "Error: " + e.read()


def addRow(self,listFeedHref,rowData):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = listFeedHref
headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

entryS = """<?xml version='1.0' ?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"""
entryD = ""
for x in rowData.keys():
entryD = entryD + "<gsx:" + x + ">" + rowData[x] + "</gsx:" + x + ">"
entryE = "</entry>"
entry = entryS + entryD + entryE
httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl,entry,headers)
#req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
except urllib2.URLError, e:
print req
print "Error: " + e.read()

def addCell(self,cellsFeedHref,cellRow,cellCol,value):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = cellsFeedHref
headers = {
'User-Agent': 'mine',
'Authorization': authString,
'Content-Type': 'application/atom+xml'
}

entry = """<?xml version='1.0' ?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gs='http://schemas.google.com/spreadsheets/2006'>
<gs:cell row='%s' col='%s' inputValue='%s' />
</entry> """ % (cellRow,cellCol,value)

httplib.HTTPConnection.debuglevel = 1 #!
req = urllib2.Request(authurl,entry,headers)
#req.add_header('Authorization',authString)
opener = urllib2.build_opener(SmartRedirectHandler)
data = ''
try:
data = opener.open(req)
except urllib2.URLError, e:
print req
print "Error: " + e.read()

def updateCell(self,cellsFeedHref,cellRow,cellCol,value):
authString = "GoogleLogin auth=%s" % (self.auth)
authurl = cellsFeedHref

entry = """<?xml version='1.0' ?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:gs='http://schemas.google.com/spreadsheets/2006'>
<gs:cell row='%s' col='%s' inputValue='%s' />
</entry> """ % (cellRow,cellCol,value)

httplib.HTTPConnection.debuglevel = 0 #!
o = urlparse(cellsFeedHref)
h = httplib.HTTPConnection(o[1])
h.putrequest('PUT',o[2])
h.putheader('User-Agent','mine')
h.putheader('Authorization',authString)
h.putheader('Content-Type','application/atom+xml')
h.putheader('Content-Length',str(len(entry)) )
h.endheaders()
h.send(entry)
return h.getresponse().read()

# execute tests
if __name__ == '__main__':
''' execute module directly to perform tests'''

# getting account info
import accountInfo
username = accountInfo.info['username']
password = accountInfo.info['password']

# initializing new spreadsheet obj
a = gSpreadsheet()

# logging into Google account
a.getAuth(username,password)

# getting a list of all spreadsheets in account
ss = a.getSpreadsheetsList()

# finding the href of spreadsheet with title 'test1'
linkFeedHref=''
for spreadsheet in ss:
if spreadsheet['title']=='test1':
linkFeedHref = spreadsheet['linkFeedHref']

# get list of worksheets in selected spreadsheet
sw = a.getWorksheets(linkFeedHref)

# get list feed for first worksheet in selected spreadsheet - query is optional parameter!
print "listFeedHref for worksheet 0:" + sw[0]["listFeedHref"]
swl = a.getWorksheetListFeed(sw[0]["listFeedHref"],"ipm>4 and hours<2")

# get cell feed for first worksheet in selected spreadsheet
print "cellsFeedHref for worksheet 0:" + sw[0]["cellsFeedHref"]
swc = a.getWorksheetCellsFeed(sw[0]["cellsFeedHref"])

# adding cell to first worksheet in selected spreadsheet in row 13, col 5
a.addCell(sw[0]["cellsFeedHref"],"12","5","5006")

# adding row to first worksheet in selected spreadsheet (gets added to end)
a.addRow(sw[0]["listFeedHref"], {"hours":"1","ipm":"50","items":"60","name":"Liz B"})

# editing contents of cell entry #37 with value 666
editHref = swc[37]["editHref"]
cRow = swc[37]["row"]
cCol = swc[37]["col"]
a.updateCell(editHref, cRow, cCol, "666")


Show details Hide details

Change log

r10 by pamela.fox on Jan 20, 2007   Diff
Un-commented the test cases
Go to: 
Project members, sign in to write a code review

Older revisions

r9 by pamela.fox on Jan 20, 2007   Diff
Added input value for cells feed
r5 by pamela.fox on Dec 27, 2006   Diff
updated
r3 by pamela.fox on Dec 01, 2006   Diff
Added a file remotely
All revisions of this file

File info

Size: 12382 bytes, 341 lines
Hosted by Google Code