3 # Copyright (c) 2017 IXIA and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
14 from six.moves.urllib.parse import urljoin
17 def getConnection(server, port):
19 Gets a Connection instance, that will be used to
20 make the HTTP requests to the application
22 connectionUrl = 'http://%s:%s/' % (server, port)
24 conn = Connection(connectionUrl, 'v0')
28 def formatDictToJSONPayload(dictionary):
30 Converts a given python dict instance to a string
31 JSON payload that can be sent to a REST API.
35 for (key, val) in dictionary.items():
40 valStr = valStr.lower()
41 optionsList.append('"%s":%s' % (key, valStr))
43 jsonPayload += ','.join(optionsList)
49 class Connection(object):
52 Class that executes the HTTP requests to the application instance.
53 It handles creating the HTTP session and executing HTTP methods.
56 kHeaderContentType = 'content-type'
57 kContentJson = 'application/json'
59 def __init__(self, siteUrl, apiVersion):
60 self.httpSession = None
62 self.url = Connection.urljoin(siteUrl, 'api')
63 self.url = Connection.urljoin(self.url, apiVersion)
65 def _getHttpSession(self):
67 This is a lazy initializer for the HTTP session.
68 It does not need to be active until it is required.
71 if self.httpSession is None:
72 self.httpSession = requests.Session()
73 return self.httpSession
76 def urljoin(cls, base, end):
77 """ Join two URLs. If the second URL is absolute, the base is ignored.
79 Use this instead of urlparse.urljoin directly so that we can customize
80 its behavior if necessary.
81 Currently differs in that it
83 1. appends a / to base if not present.
84 2. casts end to a str as a convenience
87 if base and not base.endswith('/'):
89 return urljoin(base, str(end))
91 def httpRequest(self, method, url='', data='', params={}, headers={}):
93 Method for making a HTTP request.
94 The method type (GET, POST, PATCH, DELETE) will be sent as a parameter.
95 Along with the url and request data. The HTTP response is returned
98 headers[Connection.kHeaderContentType] = Connection.kContentJson
100 absUrl = Connection.urljoin(self.url, url)
101 result = self._getHttpSession().request(method,
108 def httpGet(self, url='', data='', params={}, headers={}):
110 Method for calling HTTP GET.
111 This will return a WebObject that has the fields returned
112 in JSON format by the GET operation.
115 reply = self.httpRequest('GET', url, data, params, headers)
116 return _WebObject(reply.json())
118 def httpPost(self, url='', data='', params={}, headers={}):
120 Method for calling HTTP POST. Will return the HTTP reply.
123 return self.httpRequest('POST', url, data, params, headers)
125 def httpPatch(self, url='', data='', params={}, headers={}):
127 Method for calling HTTP PATCH. Will return the HTTP reply.
130 return self.httpRequest('PATCH', url, data, params, headers)
132 def httpDelete(self, url='', data='', params={}, headers={}):
134 Method for calling HTTP DELETE. Will return the HTTP reply.
137 return self.httpRequest('DELETE', url, data, params, headers)
140 def _WebObject(value):
142 Method used for creating a wrapper object corresponding to the JSON string
143 received on a GET request.
146 if isinstance(value, dict):
147 result = WebObject(**value)
148 elif isinstance(value, list):
149 result = WebList(entries=value)
158 Using this class a JSON list will be transformed
159 in a list of WebObject instances.
162 def __init__(self, entries=[]):
164 Create a WebList from a list of items that
165 are processed by the _WebObject function
169 self.append(_WebObject(item))
172 class WebObject(object):
175 A WebObject instance will have its fields set to correspond to
176 the JSON format received on a GET request.
179 def __init__(self, **entries):
181 Create a WebObject instance by providing a dict having a
182 property - value structure.
185 self.jsonOptions = {}
186 for (key, value) in six.iteritems(entries):
187 webObj = _WebObject(value)
188 self.jsonOptions[key] = webObj
189 self.__dict__[key] = webObj
191 def getOptions(self):
193 Get the JSON dictionary which represents the WebObject Instance
196 return self.jsonOptions