如何通过Google Drive API下载特定用户云端硬盘的文件?
Alright, let's figure out how to download files from a specific user's Google Drive using the Drive API—since right now you can only access your own account's content. Here's a clear, actionable implementation plan split into the two most common scenarios:
First off: You can't just pull files from another user's Drive out of nowhere. You need either explicit permission from the user (via file sharing) or, if you're a Google Workspace admin, use domain-wide delegation to access users' drives within your organization. Let's break both down.
This is the most straightforward use case for non-admin users.
Step 1: Get the Shared File/Folder ID
Ask the target user to share the file or folder with your Google account (the one you're using for the API). Once shared, grab the file ID from its Drive URL—look for the string betweend/and/view, e.g., inhttps://drive.google.com/file/d/123abcXYZ/view, the ID is123abcXYZ.Step 2: Authenticate with the Right Scopes
When setting up your OAuth2 authentication, make sure you request thehttps://www.googleapis.com/auth/drive.readonlyscope (orhttps://www.googleapis.com/auth/driveif you need write access later). This ensures your app has permission to read shared files your account can access.Step 3: Use the API to Download the File
Here's a Python example to download the shared file using the Drive API client library:from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload import io # Assume you've already set up OAuth2 credentials (creds) service = build('drive', 'v3', credentials=creds) # Replace with the shared file's ID target_file_id = '123abcXYZ' # Request the file media request = service.files().get_media(fileId=target_file_id) # Stream the download to a local file fh = io.FileIO('downloaded_document.pdf', 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while not done: status, done = downloader.next_chunk() print(f"Download progress: {int(status.progress() * 100)}%")This code streams the file content directly to your local system, which is efficient for large files.
If you're managing a Google Workspace domain, you can use a service account to impersonate any user in your domain and access their Drive without manual sharing.
Step 1: Set Up a Service Account with Domain-Wide Delegation
- Go to the Google Cloud Console, create a service account, and download its JSON key file.
- Enable "Domain-wide delegation" for the service account.
- Head to your Google Workspace Admin Console, navigate to Security > API controls > Domain-wide delegation, and add the service account's client ID with the scope
https://www.googleapis.com/auth/drive.readonly(or the appropriate scope for your needs).
Step 2: Impersonate the Target User
Use the service account key to authenticate and impersonate the target user. Here's how in Python:from google.oauth2 import service_account from googleapiclient.discovery import build SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] SERVICE_ACCOUNT_KEY_PATH = 'path/to/your/service-account-key.json' # The email of the user you want to impersonate TARGET_USER_EMAIL = 'user@your-domain.com' # Load service account credentials credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_KEY_PATH, scopes=SCOPES) # Impersonate the target user delegated_creds = credentials.with_subject(TARGET_USER_EMAIL) # Build the Drive API service service = build('drive', 'v3', credentials=delegated_creds)Step 3: List and Download Files
Now you can interact with the target user's Drive just like you would your own. For example, list files and download one:# List the first 10 files in the target user's Drive results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)" ).execute() items = results.get('files', []) if not items: print("No files found in the target user's Drive.") else: print("Files available:") for item in items: print(f"{item['name']} (ID: {item['id']})") # Download the first file as an example if item == items[0]: request = service.files().get_media(fileId=item['id']) fh = io.FileIO(f"{item['name']}", 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while not done: status, done = downloader.next_chunk() print(f"Downloading {item['name']}: {int(status.progress() * 100)}%")
- Permissions Matter: In scenario 1, double-check that the target user has shared the file with your account (not just "anyone with the link" unless you're using that link's ID). In scenario 2, ensure your Workspace admin has correctly authorized the service account's scopes.
- Minimize Scope: Always request the narrowest scope possible—
drive.readonlyis enough for downloading, so avoid using the fulldrivescope unless you need write access. - Rate Limits: The Drive API has quota limits—keep an eye on your usage in the Google Cloud Console to avoid getting throttled.
内容的提问来源于stack exchange,提问作者Joschi

