问题描述
我正在尝试为我的 Python 3 Google App Engine 自动创建防火墙规则。 Per their docs,我可以为此使用 Admin API(我已在 Cloud Console 中启用)。我也在 API Key 上创建了一个 the APIs & Keys/Credentials page(没有限制)。 Python library 表示我可以将此密钥用于该库。但是,当我将 API_KEY
与以下代码一起使用时,我得到:
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://appengine.googleapis.com/v1beta/apps/{my project ID}/firewall/ingressRules?key={my API Key}&alt=json returned "Request is missing required authentication credential. Expected OAuth 2 access token,login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.". Details: "Request is missing required authentication credential. Expected OAuth 2 access token,login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.">
错误中的 URL 没有用,因为我故意不尝试使用 Oauth2(矫枉过正)。这是产生上述错误的代码:
from googleapiclient.discovery import build
def set_firewall_rules(file_name):
infile = open(file_name)
service = build('appengine','v1beta',developerKey=API_KEY)
existing_rules = service.apps().firewall().ingressRules().list(appsId='{my project ID')
print(existing_rules.execute())
service.close()
return
为什么我的 API 密钥不足?是否需要更改我的应用上的设置,或者我是否必须创建一个包含范围和所有 Oauth2 内容的服务帐户?
另外,我注意到如果我将 service.close()
行移动到 print
行之前,我会得到 AttributeError: 'Http' object has no attribute 'http'
,所以我离成功至少还有 2 步之遥。它使在 bash 脚本中使用 gcloud
变得更简单...
我在带有 google-api-python-client 1.12.8 的虚拟环境中使用 Python 3.8。
解决方法
很遗憾,在调用 apps.firewall.ingressRules.list
时无法使用 API 密钥。您需要使用 OAuth,因为该方法需要以下 OAuth 范围:
- appengine.admin
- 云平台
- cloud-platform.read-only
Here 是关于使用服务帐户凭据进行身份验证的好答案。注意:
注意 scopes 参数。这定义了授予生成的凭据对象的权限。
SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'service-account-credentials.json'
from google.oauth2 import service_account
cred = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,scopes=SCOPES)
作为额外的参考,这里是 REST API:
这是 RPC 等价物:
https://cloud.google.com/appengine/docs/admin-api/reference/rpc/google.appengine.v1beta#firewall