在Cloud Function中读取Google Sheet到Pandas DataFrame无需公开的方法
可以实现,无需将Google Sheet设置为公开状态,通过Cloud Function内置的服务账号身份认证即可完成私有表格的数据读取,具体实现方案如下:
1. 前置权限配置
找到Cloud Function运行时使用的服务账号(默认服务账号格式为 <你的GCP项目ID>@appspot.gserviceaccount.com),打开目标Google Sheet的共享设置,将该服务账号邮箱添加为协作者,仅授予查看者权限即可。
2. 依赖配置
在Cloud Function的requirements.txt文件中添加如下依赖:
pandas>=2.0.0 gspread>=5.7.0 google-auth>=2.16.0
3. 代码实现
Cloud Function运行时会自动加载服务账号的默认凭证,无需手动上传密钥,示例代码如下:
import pandas as pd import gspread from google.auth import default def load_gsheet_to_df(event, context): # 配置只读权限的鉴权范围 creds, _ = default(scopes=['https://www.googleapis.com/auth/spreadsheets.readonly']) # 初始化gspread客户端 gc = gspread.authorize(creds) # 通过Sheet ID打开目标表格,Sheet ID可从Google Sheet的浏览器URL中提取 sh = gc.open_by_key("替换为你的Google Sheet ID") # 读取指定工作表,此处以第一个工作表为例 worksheet = sh.sheet1 # 转换为pandas DataFrame df = pd.DataFrame(worksheet.get_all_records()) # 后续可以自行处理df逻辑 print(f"成功读取表格,共{len(df)}行数据") return "读取完成"
方案说明
该方案全程通过GCP身份体系鉴权,不需要将Google Sheet设为公开访问,也不需要在代码中硬编码任何敏感密钥,完全符合安全合规要求。
内容的提问来源于stack exchange,提问作者Franco Piccolo
相关产品推荐
相关产品推荐

