使用Python脚本调用BigQuery rowAccessPolicies.list接口时遭遇401认证凭证缺失问题求助
解决BigQuery行访问策略API调用的401未认证问题
你遇到的401错误是因为直接用requests发起的请求没有携带BigQuery API要求的认证凭证。BigQuery的REST API需要OAuth 2.0访问令牌或者服务账号签名的请求才能通过认证,下面给你两种可行的解决办法,优先推荐第一种更简单的官方库方案:
方法一:使用Google Cloud官方Python客户端库(推荐)
Google提供了专门的BigQuery客户端库,它会自动处理认证流程,不用你手动管理token,代码更简洁也更可靠。
步骤:
- 先安装客户端库:
pip install google-cloud-bigquery
- 配置认证:
- 本地开发:在终端运行
gcloud auth application-default login,按照提示登录你的Google账号即可(需要有目标项目的BigQuery权限)。 - 生产环境:创建一个服务账号,下载JSON密钥文件,然后设置环境变量:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
- 本地开发:在终端运行
- 编写代码获取行访问策略:
from google.cloud import bigquery client = bigquery.Client(project="project123") table_ref = client.dataset("Dataset123").table("Test") row_access_policies = client.list_row_access_policies(table_ref) # 整理成你期望的JSON格式 result = {"rowAccessPolicies": []} for policy in row_access_policies: result["rowAccessPolicies"].append({ "rowAccessPolicyReference": { "projectId": policy.project, "datasetId": policy.dataset_id, "tableId": policy.table_id, "policyId": policy.policy_id }, "filterPredicate": policy.filter_predicate, "creationTime": policy.creation_time.isoformat(), "lastModifiedTime": policy.last_modified_time.isoformat() }) print(result)
方法二:手动给requests请求添加认证令牌
如果你坚持要用requests库调用REST API,可以通过google-auth库获取OAuth 2.0令牌,然后加到请求头里。
步骤:
- 安装依赖库:
pip install google-auth google-auth-httplib2
- 修改你的代码,添加认证逻辑:
import requests from google.auth import default from google.auth.transport.requests import Request # 获取默认认证凭证(会自动读取环境变量或本地登录信息) credentials, project_id = default() # 如果凭证过期,刷新令牌 if credentials.expired and credentials.refresh_token: credentials.refresh(Request()) # 获取访问令牌 auth_token = credentials.token # 发起请求时携带Authorization头 url = "https://bigquery.googleapis.com/bigquery/v2/projects/project123/datasets/Dataset123/tables/Test/rowAccessPolicies" headers = {"Authorization": f"Bearer {auth_token}"} response = requests.get(url, headers=headers) print(response.json())
补充说明:
不管用哪种方法,确保你的账号(或服务账号)拥有bigquery.rowAccessPolicies.list权限,通常可以给账号添加BigQuery Data Viewer或者更精细的Row Access Policy Viewer角色。
内容的提问来源于stack exchange,提问作者Filipe Wolfrum caeiros
相关产品推荐
相关产品推荐

