Omk*_*ara 5 google-api-python-client google-cloud-platform
我想获取计算引擎的访问令牌。通过使用此访问令牌,我想调用 REST api。将使用 python 2.0 HTTP 库调用进一步的 Rest api。(并非所有 google 库都可用,因此考虑 REST api)
您能否提供获取计算引擎访问令牌的方法?以下代码可以作为起点,但是如何从这里开始获取访问令牌尚不清楚:
from google.auth import compute_engine
credentials = compute_engine.Credentials()
Run Code Online (Sandbox Code Playgroud)
请提出不同的方法......提前致谢。
每个 Compute Engine 实例都将其元数据存储在元数据服务器上。您可以从实例内以编程方式查询此元数据服务器,以获取有关该实例的信息,例如服务帐户信息。您可以像这样从 Python 中的元数据服务器请求访问令牌:
import requests
METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/'
METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
SERVICE_ACCOUNT = 'default'
def get_access_token():
url = '{}instance/service-accounts/{}/token'.format(
METADATA_URL, SERVICE_ACCOUNT)
# Request an access token from the metadata server.
r = requests.get(url, headers=METADATA_HEADERS)
r.raise_for_status()
# Extract the access token from the response.
access_token = r.json()['access_token']
return access_token
Run Code Online (Sandbox Code Playgroud)
请注意,此示例假设您的实例使用Compute Engine 默认服务帐户。
| 归档时间: |
|
| 查看次数: |
870 次 |
| 最近记录: |