Nếu bạn chưa thiết lập API Google Drive, phạm vi và thông tin xác thực, vui lòng làm theo hướng dẫn này tại đây
Để có thể truy cập tài nguyên API, chúng tôi cần lấy mã thông báo truy cập. Vì tài nguyên API mà chúng tôi muốn truy cập chứa phạm vi nhạy cảm [truy cập tệp trong Google Drive], chúng tôi cần thực hiện xác thực trình duyệt lần đầu tiên
Trước khi bắt đầu, hãy thiết lập một virtual environment
để chứa và cài đặt tất cả các phụ thuộc cho dự án này. Chúng ta sẽ bắt đầu với việc cài đặt các thư viện
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
0 và first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
1MacBook-Pro:~ bobthedude$ virtualenv venv_google_api
MacBook-Pro:~ bobthedude$ source venv_google_api/bin/activate# install all the dependent packages
[venv_google_api] MacBook-Pro:~ bobthedude$ pip install google-api-python-client oauth2client
Tạo một thư mục trong thư mục dự án có tên là
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
2 để lưu trữ first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
3 mà bạn có thể tải xuống từ Google Console của mình. Nếu bạn không biết cách thực hiện việc này, hãy làm theo hướng dẫn này tại đâyCấu trúc dự án của bạn sẽ trông như thế này để bắt đầu.
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
4 là tệp Python chứa hướng dẫn kết nối với Google Drive APIfirst_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
Hãy viết đoạn mã cần nhập vào
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
4________số 8_______Mã thông báo truy cập của bạn sẽ được lưu trữ trong
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
6 khi xác thực trình duyệt mà tôi sẽ thực hiện sau nàyBây giờ, hãy lưu tệp và truy cập
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
7 của bạn. Thực hiện theo các lệnh bên dưới để nhận mã thông báo truy cập của bạn. Ghi chú. nếu bạn thực thi đoạn script trên từ một IDE [tôi sử dụng first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
8], bạn sẽ gặp lỗi. Lần đầu tiên duy nhất, bạn cần thực thi tập lệnh từ first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
7 của mình[venv_google_api] MacBook-Pro:~ bobthedude$ cd first_medium_project
[venv_google_api] MacBook-Pro:first_medium_project bobthedude$ python connect_to_google_drive.py# below is the output of the above command
/Users/bobthedude/virtualenv/venv_google_api/lib/python3.7/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access ./credentials/credentials.json: No such file or directory
warnings.warn[_MISSING_FILE_MESSAGE.format[filename]]Your browser has been opened to visit://accounts.google.com/o/oauth2/auth?client_id=123456789101-ab12r1abcdefjklm1a2bcdefghi12a1a.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=offline&response_type=codeIf your browser is on a different machine then exit and re-run this
application with the command-line parameter--noauth_local_webserver
Một tab trình duyệt sẽ mở sau khi thực hiện lệnh trên. Chọn tài khoản Google mà bạn đã thiết lập API và thông tin đăng nhập ở bước trước. Sau đó bấm vào Cho phép
Một lần nữa, Google sẽ nhắc bạn và yêu cầu xác nhận nếu bạn muốn cho phép Ứng dụng phương tiện đầu tiên truy cập các tệp Google Drive của mình. Tiếp tục và nhấp vào Cho phép
Nếu thành công, trình duyệt của bạn sẽ trả về một trang có nội dung sau
from apiclient import discovery0. Và nếu bạn quay lại
from httplib2 import Http
from oauth2client import client, file, tools
# define path variables
credentials_file_path = './credentials/credentials.json'
clientsecret_file_path = './credentials/client_secret.json'
# define API scope
SCOPE = '//www.googleapis.com/auth/drive'
# define store
store = file.Storage[credentials_file_path]
credentials = store.get[]# get access token
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets[clientsecret_file_path, SCOPE]
credentials = tools.run_flow[flow, store]
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
7 của mình, bạn sẽ thấy thêm 2 dòng [cho biết xác thực thành công] được in như sau/Users/bobthedude/virtualenv/venv_google_api/lib/python3.7/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access ./credentials/credentials.json: No such file or directory
warnings.warn[_MISSING_FILE_MESSAGE.format[filename]]Your browser has been opened to visit://accounts.google.com/o/oauth2/auth?client_id=123456789101-ab12r1abcdefjklm1a2bcdefghi12a1a.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=offline&response_type=codeIf your browser is on a different machine then exit and re-run this
application with the command-line parameter--noauth_local_webserverAuthentication successful.
success
Ngoài ra, bạn sẽ thấy một tệp mới
from apiclient import discovery2 được tạo trong thư mục
from httplib2 import Http
from oauth2client import client, file, tools
# define path variables
credentials_file_path = './credentials/credentials.json'
clientsecret_file_path = './credentials/client_secret.json'
# define API scope
SCOPE = '//www.googleapis.com/auth/drive'
# define store
store = file.Storage[credentials_file_path]
credentials = store.get[]# get access token
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets[clientsecret_file_path, SCOPE]
credentials = tools.run_flow[flow, store]
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
2. công việc tuyệt vời. Hiện chúng tôi đã nhận được mã thông báo truy cập mà chúng tôi có thể sử dụng để kết nối với tài nguyên API Google Drive[venv_google_api] MacBook-Pro:first_medium_project bobthedude$ ls credentials/# output as below
client_secret.json credentials.json
Bây giờ, hãy thêm một chức năng vào
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
4 của chúng tôi để truy xuất tất cả các tệp mà chúng tôi có trong Google Drive của mìnhfrom apiclient import discovery, errors
from httplib2 import Http
from oauth2client import client, file, tools
# define variables
credentials_file_path = './credentials/credentials.json'
clientsecret_file_path = './credentials/client_secret.json'
# define scope
SCOPE = '//www.googleapis.com/auth/drive'
# define store
store = file.Storage[credentials_file_path]
credentials = store.get[]
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets[clientsecret_file_path, SCOPE]
credentials = tools.run_flow[flow, store]
# define API service
http = credentials.authorize[Http[]]
drive = discovery.build['drive', 'v3', http=http]
# define a function to retrieve all files
def retrieve_all_files[api_service]:
results = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = api_service.files[].list[**param].execute[] # append the files from the current result page to our list
results.extend[files.get['files']] # Google Drive API shows our files in multiple pages when the number of files exceed 100
page_token = files.get['nextPageToken']
if not page_token:
break
except errors.HttpError as error:
print[f'An error has occurred: {error}']
break # output the file metadata to console
for file in results:
print[file]
return results
# call the function
all_files = retrieve_all_files[drive]
Bây giờ, hãy truy cập
first_medium_project
|
|__credentials
| |
| |__client_secret.json
|
|__connect_to_google_drive.py
7 của bạn và thực thi tập lệnh Python[venv_google_api] MacBook-Pro:first_medium_project bobthedude$ python connect_to_google_drive.py# output will look like this
{'kind': 'drive#file', 'id': '12345678901234TyVhFjlzOhL9MoazYiFbyABWgV9abC', 'name': 'Christmas Plan', 'mimeType': 'application/vnd.google-apps.spreadsheet'}
{'kind': 'drive#file', 'id': '12345678901234sN8zlbWAptpqNOgEihTZhgKgsAbac9', 'name': 'Event Feedback', 'mimeType': 'application/vnd.google-apps.form'}
{'kind': 'drive#file', 'id': '12345678901234URWSjdpbEABCDE', 'name': 'Workshop 2010', 'mimeType': 'application/vnd.google-apps.folder'}
Bạn có thể thấy ở phần trên, tập lệnh Python của chúng tôi đã kết nối thành công với tài nguyên API Google Drive, đã truy xuất tất cả các tệp và in siêu dữ liệu tệp
Có rất nhiều thứ khác mà bạn có thể làm với điều này. Bạn có thể thêm một vài dòng mã chấp nhận tên tệp để tập lệnh Python của bạn sẽ truy xuất siêu dữ liệu tệp cho một tệp cụ thể mà bạn quan tâm. Hãy sửa đổi hàm
from apiclient import discovery6 và xem nó trông như thế nào
from httplib2 import Http
from oauth2client import client, file, tools
# define path variables
credentials_file_path = './credentials/credentials.json'
clientsecret_file_path = './credentials/client_secret.json'
# define API scope
SCOPE = '//www.googleapis.com/auth/drive'
# define store
store = file.Storage[credentials_file_path]
credentials = store.get[]# get access token
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets[clientsecret_file_path, SCOPE]
credentials = tools.run_flow[flow, store]
# define a function to retrieve all files
def retrieve_all_files[api_service, filename_to_search]:
results = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = api_service.files[].list[**param].execute[]# append the files from the current result page to our list
results.extend[files.get['files']]# Google Drive API shows our files in multiple pages when the number of files exceed 100
page_token = files.get['nextPageToken']
if not page_token:
break
except errors.HttpError as error:
print[f'An error has occurred: {error}']
break# output the file metadata to console
for file in results:
if file.get['name'] == filename_to_search:
print[file]
break
return results, file
# call the function
filename_to_search = 'Christmas Plan'
all_files, search_file = retrieve_all_files[drive, filename_to_search]
Trong phần tiếp theo của loạt bài hướng dẫn này, tôi sẽ chỉ cho bạn cách chúng ta có thể tải xuống một trang tính cụ thể từ Google trang tính thành tệp csv. Ngoài ra, chúng tôi sẽ chuyển đổi mã ở trên thành một ứng dụng dòng lệnh, thay vì chỉ là một tập lệnh Python đơn giản