Created
August 10, 2018 17:48
-
-
Save debendraoli/abe9e1298cdbba25cb8a2fd7f8073553 to your computer and use it in GitHub Desktop.
Upload files to google drive using python
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
from apiclient.discovery import build | |
from httplib2 import Http | |
from oauth2client import file, client, tools | |
from apiclient.http import MediaFileUpload | |
import os | |
import json | |
import glob | |
import argparse | |
# @author debendraoli (github id) | |
def upload(dir): | |
global file | |
gdrive_dir = ['1xyuPy4BcxvtaBZY0Z_ShvupKB2yPlLQ3'] | |
SCOPES = 'https://www.googleapis.com/auth/drive' | |
store = file.Storage('token.json') | |
creds = store.get() | |
if not creds or creds.invalid: | |
flow = client.flow_from_clientsecrets('credentials.json', SCOPES) | |
creds = tools.run_flow(flow, store) | |
drive_service = build('drive', 'v3', http=creds.authorize(Http())) | |
images = glob.glob(dir) | |
for image in images: | |
file_metadata = { | |
'name': os.path.basename(open(image).name), | |
'parents': gdrive_dir, | |
'description': 'files backup' | |
} | |
media = MediaFileUpload(image) | |
file = drive_service.files().create( | |
body=file_metadata,media_body=media, | |
fields='id').execute() | |
print('File ID: %s' % file.get('id')) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-dir', required=True, help='Direcrory path.') | |
parser.add_argument('-ext', required=True, help='File extension. Eg.: .txt, .jpg, .png, .pdf, *') | |
args = vars(parser.parse_args()) | |
files_path = f"{args['dir']}*{args['ext']}" | |
upload(files_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment