/
upload.py
90 lines (63 loc) · 2.8 KB
/
upload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import httplib2
import pprint
import logging
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
logging.basicConfig()
# Copy your credentials from the console
CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXX'
# 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'
# when you are looking at a folder on google drive the folder will look like this:
# https://drive.google.com/?authuser=0#folders/ZZZZZZZZZZZZZZZZZZZZZZZZZZZ
# below folder to upload files to, put those characters
# from the link like above (Z's), into this string below
GOOGLE_DRIVE_FOLDER = 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZ'
if(len(sys.argv)==2):
# Path to the file to upload
#FILENAME = 'document.txt'
FILENAME = str(sys.argv[1])
if (len(FILENAME.split('/'))> 1) :
FILE = FILENAME.split('/')[1]
else:
FILE = FILENAME
#IF NOT PREVIOUSLY STORED RUN THIS CODE INSTEAD
#------------------------------------------------------
# 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)
print 'storing credentials' + str(credentials)
storage.put(credentials)
#------------------------------------------------------
#****IMPORTANT*****************************************************<<<<<<<<<<<<<
##USE THIS AFTER YOU GET THE STRING
##PREVIOUSLY STORED CREDENTIALS
#storage = Storage('a_credentials_file')
#print 'getting credentials from file'
#credentials = storage.get()
# 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)
# Insert a file
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
# File attributes
body = {'title': FILE,'description': '','mimeType': 'image/jpg'}
body['parents'] = [{'id': GOOGLE_DRIVE_FOLDER}]
#print FILE
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)
else:
print "wrong number of arguments: " +str(len(sys.argv))
print "upload.py needs 2 (example: sudo python upload.py document.txt)"