Python3如何调用Openstack Api接口

Openstack Api接口调用

Posted by Dc on January 22, 2018

Python3 requests调用Openstack Restful Api接口


前言

  之前一直使用python3 urllib3调用openstack的Restful Api接口,繁杂的代码结构,影响代码的美观,自从接触的requests这把python网络编程的瑞士小军刀,代码简练,用起来甚是舒心!
  附送requests开发文档: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
  附送openstack Restful Api接口文档:https://developer.openstack.org/zh_CN/api-guide/quick-start/

示例

import os
import requests
import json

OS_AUTH_URL = 'http://controller'
body={ 'auth': { 'identity': { 'methods': ['password'],'password': {'user': {'domain': {'name': 'default'},'name': 'admin', 'password': 'admin'} } }, 'scope': { 'project': { 'domain': { 'name': '''default''' }, 'name':  'admin' } } }}
headers={}
['Content-Type'] = 'application/json'
headers['Accept'] = '*/*'

def get_token():#获取token值
	get_token_url=OS_AUTH_URL+':35357/v3/auth/tokens'
	result=requests.post(get_token_url,headers=headers,data=json.dumps(body)).headers['X-Subject-Token']
	return result

def user_list():
	user_list_url=OS_AUTH_URL+':35357/v3/users'
	headers['X-Auth-Token']=get_token()
	result=requests.get(user_list_url,headers=headers).json()
	print(headers)
	print(result)

user_list()


很简单的api调用,如有不懂处请私信!
我的Email:zsc9602@gmail.com