kadamb
kadamb

Reputation: 1728

Not able to download google spreadsheet by google drive API using python

I am trying to download a spreadsheet file from my drive to my computer. I am able to authenticate, get list of files and even get meta-data successfully. But when I try to download the file, I get the following error :

downloading file starts
An error occurred: <HttpError 400 when requesting https://www.googleapis.com/dri
ve/v2/files/1vJetI_p8YEYiKvPVl0LtXGS5uIAx1eRGUupsXoh7UbI?alt=media returned "The
 specified file does not support the requested alternate representation.">
downloading file ends

I couldn't get any such problem or question on SO and the other methods or solutions provided on SO for downloading the spreadsheet are outdated.Those have been deprecated by Google .

Here is the code, I am using to download the file :

import httplib2
import os    
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools


from apiclient import errors
from apiclient import http

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

#SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secrets.json'
APPLICATION_NAME = 'Drive API Quickstart'


def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v2', http=http)

    file_id = '1vJetI_p8YEYiKvPVl0LtXGS5uIAx1eRGUupsXoh7UbI'

    print "downloading file starts"
    download_file(service, file_id)
    print "downloading file ends "

def download_file(service, file_id):

    local_fd = open("foo.csv", "w+")
    request = service.files().get_media(fileId=file_id)
    media_request = http.MediaIoBaseDownload(local_fd, request)

    while True:
        try:
            download_progress, done = media_request.next_chunk()
        except errors.HttpError, error:
            print 'An error occurred: %s' % error
            return
        if download_progress:
            print 'Download Progress: %d%%' % int(download_progress.progress() * 100)
        if done:
            print 'Download Complete'
            return

if __name__ == '__main__':
    main()

Upvotes: 3

Views: 1948

Answers (2)

kadamb
kadamb

Reputation: 1728

This code worked for me. I only had to download client_secret.json from google developers dashboard and keep in the same directory as python script.

And in the list_of_lists variable I got a list with each row as list.

import gspread
import json
from oauth2client.client import SignedJwtAssertionCredentials


json_key = json.load(open('client_secret.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)

gc = gspread.authorize(credentials)
sht1 = gc.open_by_key('<id_of_sheet>')
worksheet_list = sht1.worksheets()
worksheet = sht1.sheet1
list_of_lists = worksheet.get_all_values()

for row in list_of_lists :
    print row

Upvotes: 0

pinoyyid
pinoyyid

Reputation: 22286

Google spreadsheets don't have media. Instead they have exportLinks. Get the file metadata, then look in the exportlinks and pick an appropriate URL.

Upvotes: 1

Related Questions