Script Python để kết nối Google Drive bằng service account, lấy danh sách file trong một thư mục và tải các file đó về thông qua Google Drive API.
- Kết nối Google Drive bằng
credentials.json - Đọc cấu hình thư mục từ file
.env - Liệt kê file trong một folder Google Drive
- Bỏ qua các item là folder
- Chuyển dữ liệu API sang model bằng
@dataclass - Tải file từ Google Drive
- Python
>= 3.10 - Google Cloud service account có quyền đọc Google Drive
- Folder Google Drive đã được chia sẻ cho service account
git clone <your-repo-url>
cd gdrive-downloadNếu dùng uv:
uv syncHoặc dùng pip:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib python-dotenv tqdmTrong Google Cloud:
- Tạo project hoặc dùng project có sẵn
- Enable Google Drive API
- Tạo Service Account
- Tải file JSON key về
- Đổi tên thành
credentials.jsonvà đặt ở thư mục root của project
Lấy email của service account trong file JSON, sau đó share folder Google Drive cho email đó với quyền đọc.
Tạo file .env ở thư mục root:
FOLDER_ID=your_google_drive_folder_idBạn có thể lấy FOLDER_ID từ URL của folder:
https://drive.google.com/drive/folders/<FOLDER_ID>
Nếu dùng uv:
uv run python main.pyHoặc dùng Python trực tiếp:
python main.pymain.py: logic kết nối Google Drive, đọc danh sách file và tải filecredentials.json: khóa service account.env: cấu hìnhFOLDER_IDpyproject.toml: khai báo dependency của project
- Đọc biến môi trường từ
.env - Khởi tạo Google Drive service bằng service account
- Liệt kê toàn bộ file trong folder được cấu hình
- Bỏ qua các item có kiểu folder
- Convert dữ liệu sang
FileModel - Tải từng file qua Google Drive API
- Service account phải được cấp quyền truy cập vào folder cần đọc
- Project hiện đang dùng quyền
drive.readonly - Nếu thiếu
credentials.jsonhoặcFOLDER_ID, chương trình sẽ không chạy được - File log được in ra console để tiện debug
google-api-python-clientgoogle-auth-httplib2google-auth-oauthlibpython-dotenvtqdm
- Lưu file tải về ra thư mục local
- Hiển thị progress download rõ ràng hơn
- Xử lý lỗi chi tiết hơn khi tải file
- Thêm test cho phần map dữ liệu sang
FileModel