Python: google.api_core.exceptions.Forbidden: 403 访问被拒绝: BigQuery 获取 Drive 凭据时权限被拒

0 投票
1 回答
44 浏览
提问于 2025-04-14 16:14

我正在使用一个服务账号和它生成的json密钥文件,想要查询一个连接到外部Google表格的BigQuery表。这个服务账号有编辑和查看的权限,我还尝试启用Drive API的权限范围,因为我在其他相关问题中看到过这样做。这个项目的IAM中也启用了Google Drive API。但是我一直收到错误信息:google.api_core.exceptions.Forbidden: 403 访问被拒绝:BigQuery BigQuery:获取Drive凭据时权限被拒绝。

代码

from google.cloud import bigquery
from google.oauth2 import service_account
import pandas as pd

# Initialize BigQuery client
credentials = service_account.Credentials.from_service_account_file("service_account_file.json")
client = bigquery.Client(credentials=credentials)

gbq_staging_table = "Table ID" # dataset.table

query = f"""
SELECT * FROM `{gbq_staging_table}`
"""
staging_df = client.query(query).to_dataframe()

service_account_file.json

{
  "type": "service_account",
  "project_id": "projectid",
  "private_key_id": "xxxx",
  "private_key": "-----BEGIN PRIVATE KEY-----",
  "client_email": "serviceaccount.iam.gserviceaccount.com",
  "client_id": "xxxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/xxxxx",
  "scopes": ["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/bigquery"]
}

1 个回答

2

在使用 from_service_account_file() 这个函数时,scopes 需要单独传递进去,而不是放在 service_account_file.json 这个文件里。

credentials = service_account.Credentials.from_service_account_file("service_account_file.json",  scopes=["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/bigquery"])

撰写回答