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
|
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload
SCOPES = ['https://www.googleapis.com/auth/drive']
def main():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('drive', 'v3', credentials=creds)
FOLDER_ID = 'XXXXXXXXXXXXXXXXX'
file_metadata = {
'title': ['pass.pdf'],
'parents': [FOLDER_ID]
}
print(file_metadata)
media = MediaFileUpload('pass.pdf',
mimetype='application/pdf',
resumable=True)
print(media)
f = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: %s' % f.get('id'))
if __name__ == '__main__':
main() |
Partager