Created
June 16, 2017 00:55
-
-
Save aaronpolhamus/9df340f8bfbde4534ffe0523eb4b9a32 to your computer and use it in GitHub Desktop.
Python API client demo for Google Drive SDK
This file contains hidden or 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/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