为了获得已启用的GCP服务列表,我尝试按照这个service.list请求在这个链接中获取它。
这是我的密码:
import json
from requests.auth import HTTPBasicAuth
import requests
from google.oauth2 import service_account
auth = HTTPBasicAuth('myusername@gmail.com','xyz....')
url = 'https://serviceusage.googleapis.com/v1/projects/my-proj-id123/services'
headers = {
"Accept": "application/json"
}
response = requests.request(
"GET",
url,
headers=headers,
auth=auth
)
# a=json.loads(response.text)
print(response.text) 但是我发现了一个错误:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}注意事项:我需要一种方法来根据这个链接获取响应,无论是通过服务帐户还是通过链接令牌。我有服务帐户密钥(credential.json),但是我不知道在哪里放置http请求。请给我一些程序建议。
发布于 2021-12-27 18:33:28
我鼓励您在与Google的服务交互时考虑使用Google的SDK。
这些服务不仅提供了特定于语言的资源类型,方便了创建请求和响应,还提供了更简单的auth、日志记录等功能。
记录在案:
ListServicesPager --> ListServicesResponse --> ManagedServiceservices.list --> 响应 --> ManagedService设置:
PROJECT=[[YOUR-PROJECT]]
ACCOUNT=[[YOUR-ACCOUNT]]
python3 -m venv venv
source venv/bin/activate
python3 -m pip install google-auth
python3 -m pip install google-cloud-service-management
gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}
EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"
gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${EMAIL} \
--role=roles/viewer
gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL}
export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json
python3 ./main.pymain.py
import google.auth
from google.cloud import servicemanagement_v1
credentials,project = google.auth.default()
client = servicemanagement_v1.ServiceManagerClient()
# How to construct the Request
rqst = {
# Purely for example
"pageSize": 5,
# List only project's services
"consumer_id: "project:{project}".format(
project=project
)
}
# Response is a ServiceListPager
resp = client.list_services(request=rqst)
# Which is iterable
for managed_service in resp:
try:
# This is a quirk of gRPC Transcoding
# Convert a ManagedService to JSON
j=servicemanagement_v1.ManagedService.to_json(managed_service)
print(j)
except Exception as e:
print(e)产量:
{
"serviceName": "abusiveexperiencereport.googleapis.com",
"producerProjectId": ""
}
{
"serviceName": "acceleratedmobilepageurl.googleapis.com",
"producerProjectId": ""
}
{
"serviceName": "accessapproval.googleapis.com",
"producerProjectId": ""
}
...https://stackoverflow.com/questions/70497825
复制相似问题