Skip to content

Instantly share code, notes, and snippets.

@aaronpolhamus
Created June 16, 2017 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpolhamus/9df340f8bfbde4534ffe0523eb4b9a32 to your computer and use it in GitHub Desktop.
Save aaronpolhamus/9df340f8bfbde4534ffe0523eb4b9a32 to your computer and use it in GitHub Desktop.
Python API client demo for Google Drive SDK
#!/usr/bin/env python
from __future__ import print_function
import os
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store, flags) \
if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))
FILES = (
('hello.txt', None),
('hello.txt', 'application/vnd.google-apps.document'),
)
for filename, mimeType in FILES:
metadata = {'name': filename}
if mimeType:
metadata['mimeType'] = mimeType
res = DRIVE.files().create(body=metadata, media_body=filename).execute()
if res:
print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
if res:
MIMETYPE = 'application/pdf'
file_id = res['id']
print('fileId: P{}'.format(file_id))
print('mimeType: {}'.format(MIMETYPE))
data = DRIVE.files().export(fileId=file_id, mimeType=MIMETYPE).execute()
if data:
fn = '%s.pdf' % os.path.splitext(filename)[0]
with open(fn, 'wb') as fh:
fh.write(data)
print('Downloaded "%s" (%s)' % (fn, MIMETYPE))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment