问题导读
1、从Keystone获得token的方式有哪些?
2、为什么使用 Python Keystone Client 方式最好?
让我们粗略看一下,三种从Keystone获得token的方式。在尝试这三种方式之前,你得确保已经装好Keystone终端。如果还没有装好,可以看grizzly安装版本的Keystone 安装部分。
Note:这些呼叫都将请求的是Keystone v2版本。
假定你已经安装好,并且Keystone已经跑起来了:)。然后接下来我们首先要做的便是,发一个简单的cURL发送请求:
- $
- curl -d '{"auth": {"tenantName": "demo", "passwordCredentials": {"username": "demo", "password": "password"}}}' -H "Content-type: application/json" http://localhost:5000/v2.0/tokens
复制代码
其中的tenantName 是作用域名。假使你省略了这个名字,将会获得一个无作用域的token.
当请求发送完毕,主机会返回一个JSON字符串类似如下(你的可能不一样):
- {
-
- "access":
- {
-
- "token":
- {
-
- "issued_at":
- "2014-02-10T00:40:20.909222",
-
- "expires":
- "2014-02-11T00:40:20Z",
-
- "id":
- "MIIDjwYJKoZIhvcNAQcCoIIDgDC",
-
- "tenant":
- {
-
- "description":
- null,
-
- "enabled":
- true,
-
- "id":
- "8cdca733159c4bf6a622b9bb25a73ad6",
-
- "name":
- "demo"
-
- }
-
- },
-
- "serviceCatalog":
- [],
-
- "user":
- {
-
- "username":
- "demo",
-
- "roles_links":
- [],
-
- "id":
- "d5cf3796f7c04a468b5282555110ba5d",
-
- "roles":
- [
-
- {
-
- "name":
- "member"
-
- }
-
- ],
-
- "name":
- "demo"
-
- },
-
- "metadata":
- {
-
- "is_admin":
- 0,
-
- "roles":
- [
-
- "a790ff829b0e4bc29d5ca4bbc58d48f1"
-
- ]
-
- }
-
- }
-
- }
复制代码
现在假定你不想继续用python-keystoneclient,而是调用库函数urllib2的Python项目中获得作用域token,然后你可以这样做:
- from__future__
- importprint_function
-
-
-
- importurllib2
-
- importjson
-
-
-
-
-
- if__name__
- =="__main__":
-
- json_payload={
-
- "auth":
- {
-
- "tenantName":"demo",
-
- "passwordCredentials":
- {
-
- "username":"demo",
-
- "password":"password"
-
- }
-
- }
-
- }
-
-
-
- headers={'content-type':'application/json','accept':'application/json'}
-
-
-
- request=urllib2.Request(url='http://localhost:5000/v2.0/tokens',
-
- data=json.dumps(json_payload),
-
- headers=headers)
-
-
-
- keystone_response=urllib2.urlopen(request)
-
-
-
- returned_data=json.loads(keystone_response.read())
-
-
-
- ifkeystone_response.getcode()
- ==200:
-
- print(returned_data)
-
- else:
-
- print('Something
- went wrong!')
复制代码
最后一种方式是调用Requests 库,例子如下:
- from__future__
- importprint_function
-
-
-
- importrequests
-
- importjson
-
-
-
-
-
- if__name__
- =="__main__":
-
- json_payload={
-
- "auth":
- {
-
- "tenantName":"demo",
-
- "passwordCredentials":
- {
-
- "username":"demo",
-
- "password":"password"
-
- }
-
- }
-
- }
-
-
-
- headers={'content-type':'application/json','accept':'application/json'}
-
-
-
- response=requests.post(url='http://localhost:5000/v2.0/tokens',
-
- data=json.dumps(json_payload),
-
- headers=headers)
-
-
-
- ifresponse.status_code
- ==requests.codes.ok:
-
- print(response.json())
-
- else:
-
- print('Something
- went wrong!')
复制代码
和urllib2的那种方式似乎区别不大,就是少了几句代码,不过似乎更加清晰了。
当然最好还是用Python Keystone Client这种方式,比较容易上手,而且简单明了。
|