Python37运行时Cloud Functions如何获取Datastore API所需访问令牌?
Since the google.appengine module isn't available in Python 3+ Cloud Functions, the recommended approach is to use the official google-auth library—this handles authentication seamlessly in GCP managed environments like Cloud Functions. Here's a step-by-step implementation:
Step 1: Set Up Dependencies
First, add these libraries to your requirements.txt file so Cloud Functions can install them at deployment:
google-auth requests
Step 2: Full Python Code Example
This code fetches a valid access token with the required scope and triggers the Datastore export API:
import requests from google.auth import default from google.auth.transport.requests import Request def trigger_datastore_export(request): # Fetch default credentials tied to the Cloud Functions service account credentials, project_id = default(scopes=['https://www.googleapis.com/auth/datastore']) # Refresh credentials to get a valid access token if not credentials.valid: credentials.refresh(Request()) access_token = credentials.token export_endpoint = f"https://datastore.googleapis.com/v1/projects/{project_id}:export" # Configure your export settings export_payload = { "outputUrlPrefix": "gs://your-target-bucket/datastore-backups", # Replace with your bucket path # Optional: Filter specific entity kinds to export (omit to backup all entities) "entityFilter": { "kinds": ["User", "Order"] } } request_headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } # Send the export request response = requests.post(export_endpoint, json=export_payload, headers=request_headers) if response.status_code == 200: return f"Export started successfully: {response.json()['name']}" else: return f"Export failed: {response.status_code} - {response.text}"
Critical Notes
- Permissions Setup: Make sure your Cloud Functions service account has the Datastore Admin role (or the more granular
datastore.exportAdminpermission). Also, grant write access to your target Cloud Storage bucket for the Datastore service account (service-<your-project-number>@gcp-sa-datastore.iam.gserviceaccount.com). - Scope Flexibility: Using
https://www.googleapis.com/auth/cloud-platforminstead of the Datastore-specific scope works too—it's a broad scope that covers all GCP services including Datastore. - Security Best Practice: This method uses GCP's metadata server to fetch temporary credentials, so you never need to hardcode service account keys in your function.
Why This Works
In GCP managed environments like Cloud Functions, the google-auth library automatically pulls credentials from the runtime environment, replacing the deprecated App Engine app_identity module. This is the official, secure way to handle authentication for GCP API calls in Python 3+.
内容的提问来源于stack exchange,提问作者Prashant Jamkhande

