Python:如何使用请求库访问googleappengine上托管的restplusapi?

2024-04-26 00:05:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用flask restplus构建了一个restapi,并用swagger文档进行了测试,它看起来功能齐全,工作正常。我现在想使用python请求库测试API,但出现以下错误:

Invalid IAP credentials: empty token

我想这是因为我没有授权使用凭据。我确实可以访问服务帐户凭据json文件,但我只是想知道如何将其传递到请求中?你知道吗

代码示例:

url = 'https://crosssellapi-dot-dao-aa-poc-uyim.appspot.com/auth/login'

r = requests.get(url, headers={'accept': 'application/json'})

提前谢谢。你知道吗


Tags: 文档tokenrestapirestapijsonurlflask
1条回答
网友
1楼 · 发布于 2024-04-26 00:05:36

我认为最好的方法是使用python的google-auth库。你知道吗

$ pip install google-auth

我建议create一个服务帐户,给它角色IAP secured Web App User,然后下载该服务帐户的JSON密钥。你知道吗

转到API's&;Services>;凭据并复制要用于API的OAuth 2.0客户端的Client ID。你知道吗

最后,使用此代码段发出请求:

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

SERVICE_FILENAME = '/path/to/your/service_account_key.json'
API_URL = 'https://YOUR_API_URL'
AUDIENCE = 'YOUR_OAUTH_CLIENT_ID'

credentials = service_account.IDTokenCredentials.from_service_account_file(SERVICE_FILENAME, target_audience=AUDIENCE)

session = AuthorizedSession(credentials)

r = session.get(API_URL, headers={'accept': 'application/json'})

print(r.text)

如果您想了解更多关于google-auth的信息,请查看this。你知道吗

相关问题 更多 >