如何利用Google Cloud ADC通过Python以个人账号访问Google Drive API及Workspace资源
用Python通过ADC以个人账号访问Google Workspace API(Drive/Sheets等)
前提准备
- 安装必要Python库:
google-api-python-client、google-auth、google-auth-oauthlib、google-auth-httplib2 - 在Google Cloud控制台创建项目,启用Drive API和Sheets API
- 配置OAuth 2.0客户端ID(类型选「桌面应用」),下载JSON格式的凭据文件
配置ADC使用个人账号凭据
ADC会按优先级查找凭据,要让它加载个人账号的OAuth凭据,有两种实用方式:
方式1:通过环境变量指定凭据文件
- 将下载的OAuth客户端凭据JSON文件放在本地路径(如
~/credentials.json) - 设置环境变量:
- Linux/macOS:
export GOOGLE_APPLICATION_CREDENTIALS="~/credentials.json" - Windows(PowerShell):
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\path\to\credentials.json"
- Linux/macOS:
- 首次运行脚本时,会自动打开浏览器引导你登录个人Google账号,授权后生成
token.json文件,后续运行无需重复登录
方式2:代码中显式加载凭据
若不想依赖环境变量,可在代码里直接指定路径:
from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os # 定义API权限范围,按需调整 SCOPES = [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/spreadsheets.readonly' ] creds = None # 检查是否有已保存的有效token if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 无有效凭据时引导授权 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # 保存token供后续使用 with open('token.json', 'w') as token: token.write(creds.to_json())
对接Drive/Sheets API示例
访问Google Drive
from googleapiclient.discovery import build # 构建Drive服务实例 drive_service = build('drive', 'v3', credentials=creds) # 示例:列出Drive中前10个文件 results = drive_service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('未找到文件。') else: print('文件列表:') for item in items: print(f"{item['name']} ({item['id']})")
访问Google Sheets
# 构建Sheets服务实例 sheets_service = build('sheets', 'v4', credentials=creds) # 示例:读取指定表格的A1:B2范围数据 SPREADSHEET_ID = '你的表格ID' RANGE_NAME = 'Sheet1!A1:B2' result = sheets_service.spreadsheets().values().get( spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('未找到数据。') else: print('表格数据:') for row in values: print(row)
注意事项
- 权限范围按需申请,避免过度授权(如只读需求就不要用读写权限)
token.json包含刷新令牌,不要随意分享- 如需更换账号或授权过期,删除
token.json后重新运行脚本即可重新授权
内容的提问来源于stack exchange,提问作者Kristofer
相关产品推荐
相关产品推荐

