You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python37运行时Cloud Functions如何获取Datastore API所需访问令牌?

Solution for Getting OAuth2 Access Token in Python 3.7 Cloud Functions for Datastore Export

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.exportAdmin permission). 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-platform instead 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:23:16