a quick ugly snippete to download a gdrive file programmatically

#!/usr/bin/python
import httplib2
import pprint
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
# Copy your credentials from the console
CLIENT_ID = ''
CLIENT_SECRET = ''
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Path to the file to upload
FILENAME = 'document.txt'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
from apiclient import errors
# ...
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
return None
else:
# The file doesn't have any content stored on Drive.
return None
a = open('download', 'wb')
a.write(download_file(drive_service, drive_service.files().get(fileId='0BxL9MTWmR1kISG04eThNcGJlcFU').execute()))
view raw drivedl.py hosted with ❤ by GitHub

Leave a comment