本地用Google API Python库时,如何通过Google ADC切换多用户账户?
解决多Google用户账户同时认证访问Analytics的方法
核心思路
放弃依赖ADC的默认认证逻辑,改用OAuth 2.0授权码流程,为每个Google用户单独生成并保存本地凭据文件,访问对应账户时直接加载指定凭据即可,无需反复登录切换。
具体实现步骤
1. 为每个用户生成独立的OAuth凭据文件
首先需要为每个目标Google账户生成专属的本地凭据:
- 登录Google Cloud Console(任意Cloud账户均可,仅用于创建OAuth客户端ID),创建桌面应用类型的OAuth客户端ID,下载对应的
client_secret.json文件。 - 运行以下代码,为每个用户生成单独的凭据文件(如
user1_credentials.json、user2_credentials.json):
from google_auth_oauthlib.flow import InstalledAppFlow from google.oauth2.credentials import Credentials # 替换为Analytics API所需的权限范围 SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] # 生成用户1的凭据(运行时会弹出浏览器,登录用户1的Google账号完成授权) flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', SCOPES) credentials = flow.run_local_server(port=0) with open('user1_credentials.json', 'w') as f: f.write(credentials.to_json()) # 重复上述流程生成用户2的凭据 flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', SCOPES) credentials = flow.run_local_server(port=0) with open('user2_credentials.json', 'w') as f: f.write(credentials.to_json())
每运行一次生成逻辑,浏览器会自动弹出登录界面,选择对应Google账户完成授权,授权后的凭据将保存到本地JSON文件。
2. 加载指定凭据访问对应Analytics账户
后续需要访问不同账户时,直接加载对应凭据文件创建API客户端即可实现多账户并行访问:
from google.oauth2.credentials import Credentials from googleapiclient.discovery import build # 加载用户1的凭据,访问对应的Analytics账户1 creds_user1 = Credentials.from_authorized_user_file('user1_credentials.json', SCOPES) service_user1 = build('analyticsreporting', 'v4', credentials=creds_user1) # 调用API获取数据示例 response1 = service_user1.reports().batchGet( body={ 'reportRequests': [ { 'viewId': '替换为用户1的Analytics视图ID', 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}] } ] } ).execute() # 加载用户2的凭据,访问对应的Analytics账户2 creds_user2 = Credentials.from_authorized_user_file('user2_credentials.json', SCOPES) service_user2 = build('analyticsreporting', 'v4', credentials=creds_user2) # 调用API获取数据示例 response2 = service_user2.reports().batchGet( body={ 'reportRequests': [ { 'viewId': '替换为用户2的Analytics视图ID', 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}] } ] } ).execute()
3. 关键注意事项
- 每个凭据文件与对应的Google账户绑定,只要凭据未过期(或自动刷新机制有效),即可直接复用,无需再次登录。
- 若凭据过期,代码会自动尝试刷新(前提是
client_secret.json配置正确),刷新失败时才需要重新授权。 - 务必妥善保管
client_secret.json和用户凭据文件,避免泄露。
关于之前ADC方法无效的原因
ADC的gcloud auth application-default login生成的凭据仅绑定单个用户,且默认只会读取环境变量指定或默认路径下的单个凭据文件,无法同时加载多账户凭据。而手动管理每个用户的OAuth凭据文件,可明确指定要使用的账户身份,完美适配多账户并行访问的需求。
内容的提问来源于stack exchange,提问作者Fanylion
相关产品推荐
相关产品推荐

