Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: How do i download a file from Google drive using api

I would like to download a file in google drive to my system,using google drive api. How can i implement this ?

according to example given at https://developers.google.com/drive/v2/reference/files/get#examples

def print_file(service, file_id):

 """Print a file's metadata.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to print metadata for.
  """
  try:
    file = service.files().get(fileId=file_id).execute()

    print 'Title: %s' % file['title']
    print 'MIME type: %s' % file['mimeType']
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp

I am able to find the file , But how can i download it locally to my machine ?

like image 326
Dhanya M Avatar asked Feb 03 '15 20:02

Dhanya M


People also ask

How do I download files from Google API?

To download a file stored on Google Drive, use the files. get method with the ID of the file to download and the alt=media URL parameter. The alt=media URL parameter tells the server that a download of content is being requested.

How do I download a file using API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.


2 Answers

just write the content variable to a file instead of returning the content

fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()
like image 184
Akhil Nadh PC Avatar answered Nov 03 '22 07:11

Akhil Nadh PC


I think you should probably check out this:

http://pythonhosted.org/PyDrive/

The code seems like it is easier

# Initialize GoogleDriveFile instance with file id.
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png') # Download file as 'catlove.png'.

# Initialize GoogleDriveFile instance with file id.
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# content: '{"firstname": "Claudio", "lastname": "Afshar"}'
like image 25
Nicholas Huang Avatar answered Nov 03 '22 06:11

Nicholas Huang