Module method_call
[hide private]
[frames] | no frames]

Source Code for Module method_call

  1  # -*- encoding: utf8 -*-
 
  2  """
 
  3      method_call module.
 
  4      
 
  5      This module is used to perform the calls to the AX RESTful interface.
 
  6      
 
  7      Author: Richard Zhang, A10 Networks (c)
 
  8      e-mail: rzhang@a10networks.com
 
  9      Date  : 03/04/2012
 
 10      
 
 11  """ 
 12  import urllib2 
 13  import urllib 
 14  import json 
 15  from xml.etree.ElementTree import XML 
 16  from base import AxObject, AxError, AxAPIError 
 17  
 
 18  REST_URL = "/services/rest/V2/" 
 19  AXAPI_DEVICE = "192.168.210.239" 
 20  AXAPI_SESSION_ID = "" 
 21  AXAPI_LOGIN = 0 
 22  
 
23 -class AxApiContext(AxObject):
24 25 __display__ = ["session_id", "is_login", "device_ip", "username"] 26
27 - def __init__(self, device_ip, username, password):
28 params = dict(device_ip=device_ip, username=username, password=password, is_login=False) 29 AxObject.__init__(self, **params)
30
31 - def authentication(self):
32 global AXAPI_SESSION_ID, AXAPI_DEVICE, AXAPI_LOGIN 33 AXAPI_DEVICE = self.device_ip 34 AXAPI_SESSION_ID = "" 35 AXAPI_LOGIN = 0 36 resp = call_api(self, method="authenticate", username=self.username, password=self.password) 37 xml_s = XML(resp) 38 for node in xml_s.findall('session_id'): 39 self.session_id = node.text 40 self.is_login = True 41 _set_session_id(self.session_id, self.device_ip) 42 break 43 return self
44
45 - def switchContext(self):
46 if self.is_login == False: 47 self.authentication() 48 else: 49 _set_session_id(self.session_id, self.device_ip)
50
51 -def call_api(axobjectinstance, **args):
52 """ 53 Performs the GET/POST calls to the aXAPI REST interface. 54 55 Arguments : 56 method : The name of aXAPI call. 57 format : (optional) Specify the aXAPI format, json/url. The default is "url". 58 post_data : (optional) The POST data for the REST create/update/delete transactions. 59 args : the arguments to pass to the method. 60 """ 61 62 if AXAPI_LOGIN == 1: 63 args["session_id"] = AXAPI_SESSION_ID 64 65 if args.has_key("post_data"): 66 data = args["post_data"] 67 del args["post_data"] 68 url_str = _get_request_url()+"?"+urllib.urlencode(args) 69 else: 70 data = urllib.urlencode(args) 71 url_str = _get_request_url() 72 print data 73 print url_str 74 75 resp = _send_request(url_str, data) 76 print resp 77 if args.has_key("format"): 78 fmt = args["format"] 79 if fmt == "json": 80 # handle the json response to build the dict 81 resp = json.loads(resp) 82 else: 83 # handle the xml/url response into the dict 84 resp = _XmlDict(XML(resp), axobjectinstance.__xml_convrt__) 85 print resp 86 87 return resp
88
89 -def _set_session_id(session_id, device_ip):
90 global AXAPI_SESSION_ID, AXAPI_DEVICE, AXAPI_LOGIN 91 AXAPI_SESSION_ID = session_id 92 AXAPI_DEVICE = device_ip 93 AXAPI_LOGIN = 1
94
95 -def _get_request_url() :
96 return "https://" + AXAPI_DEVICE + ":443" + REST_URL
97
98 -def _send_request(url,data):
99 req = urllib2.Request(url,data) 100 try : 101 return urllib2.urlopen(req).read() 102 except urllib2.HTTPError , e: 103 raise AxError( e.read().split('&')[0] )
104
105 -class _XmlList(list):
106 - def __init__(self, aList, assistant_dict):
107 for element in aList: 108 if len(element): 109 # treat like dict 110 #if len(element) == 1 or element[0].tag != element[1].tag: 111 # self.append(XmlDictConfigWithAssistant(element, assistant_dict)) 112 # treat like list 113 #elif element[0].tag == element[1].tag: 114 # self.append(XmlListConfigWithAssistant(element, assistant_dict)) 115 if assistant_dict.has_key(element.tag): 116 self.append( _XmlList(element, assistant_dict) ) 117 else: 118 self.append( _XmlDict(element, assistant_dict) ) 119 elif element.text: 120 text = element.text.strip() 121 if text.isdigit(): 122 self.append(int(element.text)) 123 else: 124 self.append(text)
125
126 -class _XmlDict(dict):
127 ''' 128 Example usage: 129 130 >>> tree = ElementTree.parse('your_file.xml') 131 >>> root = tree.getroot() 132 >>> xmldict = _XmlDictConvertWithAssistant(root, assistant_dict) 133 134 Or, if you want to use an XML string: 135 136 >>> root = ElementTree.XML(xml_string) 137 >>> xmldict = _XmlDictConvertWithAssistant(root, assistant_dict) 138 139 And then use xmldict for what it is... a dict. 140 '''
141 - def __init__(self, parent_element, assistant_dict):
142 if parent_element.items(): 143 self.update(dict(parent_element.items())) 144 for element in parent_element: 145 if len(element): 146 # treat like dict - we assume that if the first two tags 147 # in a series are different, then they are all different. 148 #if len(element) == 1 or element[0].tag != element[1].tag: 149 # aDict = XmlDictConfigWithAssistant(element, assistant_dict) 150 if assistant_dict.has_key(element.tag): 151 aDict = _XmlList(element, assistant_dict) 152 # treat like list - we assume that if the first two tags 153 # in a series are the same, then the rest are the same. 154 else: 155 # here, we put the list in dictionary; the key is the 156 # tag name the list elements all share in common, and 157 # the value is the list itself 158 aDict = _XmlDict(element, assistant_dict) 159 # if the tag has attributes, add those to the dict 160 if element.items(): 161 #aDict.update(dict(element.items())) 162 aDict.update(element.items()) 163 self.update({element.tag: aDict}) 164 # this assumes that if you've got an attribute in a tag, 165 # you won't be having any text. This may or may not be a 166 # good idea -- time will tell. It works for the way we are 167 # currently doing XML configuration files... 168 elif element.items(): 169 self.update({element.tag: dict(element.items())}) 170 # finally, if there are no child tags and no attributes, extract 171 # the text 172 else: 173 if assistant_dict.has_key(element.tag): 174 # add the empty list 175 self.update({element.tag: []}) 176 elif element.text == None: 177 self.update({element.tag: ''}) 178 elif element.text.isdigit(): 179 self.update({element.tag: int(element.text)}) 180 else: 181 self.update({element.tag: element.text})
182