/ 前言 /
在ZStack的API中, 大多数的API返回的是一个任务结果查询地址, 此时我们就需要根据这个地址轮训去查询任务状态及结果
{
"location": "http://localhost:8080/v1/api-jobs/967a26b7431c49c0b1d50d709ef1aef3"
}
/ API /
-
API名称
创建云主机规格(CreateInstanceOffering)
-
请求方式
POST
zstack/v1/instance-offerings
-
curl示例
curl -H "Content-Type: application/json" \ -H "Authorization: OAuth b86c9016b4f24953a9edefb53ca0678c" \ -X POST -d '{"params":{"name":"instanceOffering","cpuNum":2.0,"memorySize":2097152.0," sortKey":0.0,"type":"UserVm"}}' \ http://localhost:8080/zstack/v1/instance-offerings
-
返回示例
{"inventory": { "uuid": "d04e02a97d6c4ad0b0acee2a2f6c7084", "name": "instanceOffering1", "cpuNum": 2.0, "cpuSpeed": 1.0, "type": "UserVm", "allocatorStrategy": "Mevoco", "createDate": "Jun 7, 2017 9:20:40 PM", "lastOpDate": "Jun 7, 2017 9:20:40 PM", "state": "Enabled" }}
/ 代码 /
ZStack中, 大多数的API在调用后返回的是
user_name = 'admin'
user_password='password'
host = 'http://localhost:8080/'
# 创建计算规格
def create_instance_offerings(session_uuid):
data = json.dumps({
"params": {
"name": "instanceOffering",
# cpu数量
"cpuNum": 2.0,
# 内存大小, 以B为单位
"memorySize": 104857600.0}})
url = host + 'zstack/v1/instance-offerings'
headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
response = requests.post(url, data, headers=headers)
offer_uuid = deal_response(response, True)
if offer_uuid:
return offer_uuid
# 处理返回数据
def deal_response(response, is_return):
if response:
rsp = json.loads(response.text)
if rsp:
print('rsp : {%s}' % rsp)
json_str = query_until_done(rsp)
if json_str:
if not json_str.has_key('error'):
if is_return:
return json_str['inventory']['uuid']
else:
return True
return False
# 轮询查询API结果
def query_until_done(rsp):
# 截取任务id, 替换请求地址
if rsp.has_key('location'):
location = rsp['location']
job_uuid = location.split('/')[-1]
if job_uuid:
while True:
url = host + "zstack/v1/api-jobs/" + location.split('/')[-1]
response = requests.get(url)
text = response.text
print(text)
if text != '{}':
print('url : {%s}' % url)
return json.loads(text)
if __name__ == '__main__':
session_uuid = login()
if session_uuid:
# 创建计算规格
instance_uuid = create_instance_offerings(session_uuid)