-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupload.py
executable file
·106 lines (85 loc) · 2.24 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/python3
import argparse
import json
import mimetypes
import os.path
import requests
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
parser = argparse.ArgumentParser()
parser.add_argument('file', metavar='FILE')
parser.add_argument('folder', metavar='FOLDER_ID')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
file_path = args.file
file_obj = open(file_path, mode='rb')
file_name = os.path.basename(file_path)
file_mime_type = mimetypes.guess_type(file_path)[0]
### client secret ###
client = None
client_name = 'client_secret.json'
client_path = os.path.join(script_dir, client_name)
with open(client_path, 'r') as f:
client = json.load(f)
assert client is not None and 'installed' in client
client = client['installed']
assert 'client_id' in client
if args.verbose:
print('=== client id ===')
print(client['client_id'])
print()
assert 'client_secret' in client
if args.verbose:
print('=== client secret ===')
print(client['client_secret'])
print()
### refresh token ###
refresh_token = None
refresh_name = 'refresh_token.txt'
refresh_path = os.path.join(script_dir, refresh_name)
with open(refresh_path, mode='r') as f:
refresh_token = f.read().rstrip()
if args.verbose:
print('=== refresh token ===')
print(refresh_token)
print()
### access token ###
r = requests.post('https://accounts.google.com/o/oauth2/token', data={
'client_id': client['client_id'],
'client_secret': client['client_secret'],
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
})
r = r.json()
assert 'error' not in r, r['error']
access_token = r['access_token']
if args.verbose:
print('=== access token ===')
print(access_token)
print()
### upload file ###
r = requests.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', files={
'metadata': (
None,
json.dumps({
'name': file_name,
'parents': [
args.folder,
],
}),
'application/json; charset=UTF-8'
),
'file': (
file_name,
file_obj,
file_mime_type,
),
}, headers={
'Authorization': 'Bearer ' + access_token,
})
r = r.json()
assert 'error' not in r, '{} - {}'.format(r['error']['code'], r['error']['message'])
if args.verbose:
print('=== file id ===')
print(r['id'])
print()