-
-
Save mtik00/a91825f0e58a81bb8afa 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 | |
import urllib | |
import urllib2 | |
class Spreadsheet(object): | |
def __init__(self, key): | |
super(Spreadsheet, self).__init__() | |
self.key = key | |
class Client(object): | |
def __init__(self, email, password, apps_domain=None): | |
super(Client, self).__init__() | |
self.apps_domain = apps_domain | |
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"): | |
if self.apps_domain: | |
url = "https://docs.google.com/a/{domain}/spreadsheets/d/{key}/export?exportFormat={format}".format( | |
domain=self.apps_domain, key=spreadsheet.key, format=format) | |
else: | |
url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key={key}&exportFormat={format}&gid={gid}".format( | |
key=spreadsheet.key, gid=gid, format=format) | |
headers = { | |
"Authorization": "GoogleLogin auth=" + self.get_auth_token(), | |
"GData-Version": "3.0" | |
} | |
req = urllib2.Request(url, headers=headers) | |
return urllib2.urlopen(req) | |
if __name__ == "__main__": | |
import getpass | |
format = "xlsx" | |
domain = raw_input("Enter the apps domain (enter if None): ").strip() | |
email = raw_input("Enter your email: ").strip() | |
password = getpass.getpass("Enter your password: ") | |
spreadsheet_id = raw_input("Enter the sheet ID: ") | |
# Create client and spreadsheet objects | |
gs = Client(email, password, apps_domain=domain) | |
ss = Spreadsheet(spreadsheet_id) | |
# Request a file-like object containing the spread sheet's contents | |
req = gs.download(ss, format=format) | |
try: | |
attachment = next((x for x in req.info().headers if 'attachment' in x)) | |
fname = re.search('filename="(.*?)"', attachment).group(1) | |
except AttributeError, StopIteration: | |
fname = "sheet.%s" % format | |
with open(fname, "wb") as fh: | |
fh.write(req.read()) | |
print "[%s] downloaded" % fname |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment