Created
April 4, 2015 20:27
-
-
Save sysbot/6edec6bdfade0bf4c69b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import re, urllib, urllib2 | |
class Spreadsheet(object): | |
def __init__(self, key, gid): | |
super(Spreadsheet, self).__init__() | |
self.key = key | |
self.gid = gid | |
class Client(object): | |
def __init__(self, email, password): | |
super(Client, self).__init__() | |
self.email = email | |
self.password = password | |
def _get_auth_token(self, email, password, source, service): | |
url = "https://www.google.com/accounts/ClientLogin" | |
params = { | |
"Email": email, "Passwd": password, | |
"service": service, | |
"accountType": "HOSTED_OR_GOOGLE", | |
"source": source | |
} | |
req = urllib2.Request(url, urllib.urlencode(params)) | |
return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0] | |
def get_auth_token(self): | |
source = type(self).__name__ | |
return self._get_auth_token(self.email, self.password, source, service="wise") | |
def download(self, spreadsheet, gid=0, format="csv"): | |
url_format = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s&gid=%i" | |
headers = { | |
"Authorization": "GoogleLogin auth=" + self.get_auth_token(), | |
"GData-Version": "3.0" | |
} | |
req = urllib2.Request(url_format % (spreadsheet.key, format, spreadsheet.gid), headers=headers) | |
return urllib2.urlopen(req) | |
if __name__ == "__main__": | |
import getpass | |
import csv | |
import yaml | |
import os | |
email = os.environ['GOOGLE_APP_EMAIL'] | |
password = os.environ['GOOGLE_APP_PASSWORD'] | |
spreadsheet_id = os.environ['GOOGLE_APP_SPREADSHEET_ID'] # (spreadsheet id here) | |
tab_id = os.environ['GOOGLE_APP_SPREADSHEET_TAB_ID'] # (tab id, or gid) | |
# Create client and spreadsheet objects | |
gs = Client(email, password) | |
ss = Spreadsheet(spreadsheet_id,int(tab_id)) | |
# Request a file-like object containing the spreadsheet's contents | |
csv_file = gs.download(ss) | |
# Parse as CSV and print the rows | |
for row in csv.reader(csv_file): | |
print ",".join(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment