如何获取api access token,调用rest api (以容器镜像为例)
【摘要】 如何获取api access token,调用rest api (以容器镜像为例)
第一步: 安装SDK.
参考 https://support.huaweicloud.com/devg-sdk/zh-cn_topic_0070637133.html
仿照官方的例子创建connection
import json
from openstack import connection
import requests
# create connection
username = "XXX"
password = "XXX"
projectId = "XXX" # tenant ID
userDomainId = "XXX" # user account ID
auth_url = 'https://iam.cn-east-2.myhuaweicloud.com'
conn = connection.Connection(
auth_url=auth_url,
user_domain_id=userDomainId,
project_id=projectId,
username=username,
password=password)
第二步: 从connection 中调用iam 的api获取token
def get_auth_headers(conn):
session = conn.session
auth_headers = session.get_auth_headers()
return auth_headers
第三步: 用获得的token,调用想访问的api。
也可以用利用 auth_headers 中的 X-Auth-Token 其他rest client 来访问。
以下代码,获得容器镜像服务的列表。
api 参考 https://support.huaweicloud.com/api-swr/swr_02_0034.html
def get_response(api):
swr_url = "https://swr-api.cn-east-2.myhuaweicloud.com" # endpoint url
headers = get_auth_headers(conn)
# this line is optional
# headers['Content-Type'] = 'application/json;charset=utf8'
r = requests.get(swr_url + api, headers=headers)
return r.text
if __name__ == "__main__":
repos_api = "/v2/manage/repos?filter='center::self'"
text = get_response(repos_api)
print(text)
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
热门文章
评论(0)