Created
May 13, 2013 03:13
-
-
Save akira093/5565946 to your computer and use it in GitHub Desktop.
This file contains 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/python | |
#coding:utf8 | |
import httplib2 | |
import pprint | |
import cPickle | |
from apiclient.discovery import build | |
from apiclient.http import MediaFileUpload | |
from oauth2client.client import OAuth2WebServerFlow | |
# Copy your credentials from the APIs 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' | |
def get_drive_service( | |
credentials = None, | |
client_id = None, client_secret = None, | |
oauth_scope = None, redirect_uri = None): | |
if credentials == None: | |
# 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) | |
with open("credentials", "w") as f: | |
cPickle.dump(credentials, f) | |
# Create an httplib2.Http object and authorize it with our credentials | |
http = httplib2.Http() | |
http = credentials.authorize(http) | |
return build('drive', 'v2', http=http) | |
try: | |
with open("credentials", "r") as f: | |
credentials = cPickle.load(f) | |
except Exception as e: | |
credentials = None | |
drive_service = get_drive_service(credentials, CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) | |
# Insert a file | |
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True) | |
body = { | |
'title': 'My document', | |
'description': 'A test document', | |
'mimeType': 'text/plain' | |
} | |
# upload txt | |
file = drive_service.files().insert(body=body, media_body=media_body).execute() | |
# list all file/directory | |
pprint.pprint(drive_service.files().list().execute()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment