Tutorial Dasar Upload File Ke Google Drive Menggunakan Python

March 03, 2019


Seperti yang sudah diketahui bahwa google drive adalah salah satu layanan cloud untuk menyimpan dan berbagi file. Google telah menyediakan API untuk manajemen Google Drive dengan menggunakan beberapa bahasa seperti Go, Java, Javascript (Node Js), PHP, Python dan Ruby.

Pada artikel ini saya akan membahas bagaimana cara untuk mengupload file ke Google Drive menggunakan Python.

Struktur Folder:

[Folder]
-- testUpload.py
-- credentials.json
-- token.pickle (akan muncul otomatis setelah autentikasi)
-- 111sample.pdf



1. Aktifasi dan Konfigurasi API Google Drive

Langkah tercepat untuk mengaktifkan layanan google drive adalah dengan cara mengunjungi halaman ofisial https://developers.google.com/drive/api/v3/quickstart/python

Klik tombol [Enable The Drive API] kemudian download dan simpan konfigurasi file JSON nya

Enable Google Drive API

Download Client Configuration File

2. Install Client Library Menggunakan Perintah pip / pip3

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

3. Buat File Python

Buat file python baru dengan nama testUpload.py download disini

from __future__ import print_function
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 googleapiclient.http import MediaFileUpload, MediaIoBaseDownload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']

def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
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()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)


file_metadata = {'name': '111sample.pdf'}
# file_metadata = {'name': '111sample.pdf',
# 'parents': ['1OPKOAFatLfHakCZfPPuZ3sF3CzHv8NCO']}
media = MediaFileUpload(os.path.abspath(
"111sample.pdf"), mimetype='application/pdf')
file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()

if __name__ == '__main__':
main()
from __future__ import print_functionimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] def main():     """Shows basic usage of the Drive v3 API.     Prints the names and ids of the first 10 files the user has access to.     """     creds = None     # The file token.pickle stores the user's access and refresh tokens, and is     # created automatically when the authorization flow completes for the first     # time.     if os.path.exists('token.pickle'):         with open('token.pickle', 'rb') as token:             creds = pickle.load(token)     # If there are no (valid) credentials available, let the user log in.     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()         # Save the credentials for the next run         with open('token.pickle', 'wb') as token:             pickle.dump(creds, token)     service = build('drive', 'v3', credentials=creds)     # Call the Drive v3 API     results = service.files().list(         pageSize=10, fields="nextPageToken, files(id, name)").execute()     items = results.get('files', [])     if not items:         print('No files found.')     else:         print('Files:')         for item in items:             print(u'{0} ({1})'.format(item['name'], item['id'])) if __name__ == '__main__':     main()
from __future__ import print_functionimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] def main():     """Shows basic usage of the Drive v3 API.     Prints the names and ids of the first 10 files the user has access to.     """     creds = None     # The file token.pickle stores the user's access and refresh tokens, and is     # created automatically when the authorization flow completes for the first     # time.     if os.path.exists('token.pickle'):         with open('token.pickle', 'rb') as token:             creds = pickle.load(token)     # If there are no (valid) credentials available, let the user log in.     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()         # Save the credentials for the next run         with open('token.pickle', 'wb') as token:             pickle.dump(creds, token)     service = build('drive', 'v3', credentials=creds)     # Call the Drive v3 API     results = service.files().list(         pageSize=10, fields="nextPageToken, files(id, name)").execute()     items = results.get('files', [])     if not items:         print('No files found.')     else:         print('Files:')         for item in items:             print(u'{0} ({1})'.format(item['name'], item['id'])) if __name__ == '__main__':     main()


4. Jalankan Script testUpload.py

python testUpload.py

Ketika dijalankan maka akan muncul URL pada CMD dan browser


Silahkan login untuk autentikasi user. Setelah proses authentikasi berhasil maka file pdf dengan nama 111sample.pdf akan diupload ke google drive.

Jika ingin mengupload ke folder tertentu maka silahkan ubah
file_metadata = {'name': '111sample.pdf'}

menjadi

file_metadata = {'name': '111sample.pdf',
'parents': ['0B-q8vCvDiVpJaFNkVm9yZWMtSlk']}

parents adalah id URL dari folder

https://drive.google.com/drive/folders/0B-q8vCvDiVpJaFNkVm9yZWMtSlk

4 comments:

  1. dengan nodejs express dong kak

    ReplyDelete

  2. error bro

    Traceback (most recent call last):
    File "Upload.py", line 48, in
    main()
    File "Upload.py", line 45, in main
    fields='id').execute()
    File "C:\xampp\Python\GDRIVE~1\env\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
    File "C:\xampp\Python\GDRIVE~1\env\lib\site-packages\googleapiclient\http.py", line 856, in execute
    raise HttpError(resp, content, uri=self.uri)
    googleapiclient.errors.HttpError:

    ReplyDelete
  3. Klo download gimna caranya gan ?

    ReplyDelete

Powered by Blogger.