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
10 from urlparse import urljoin
14 def getConnection(server, port):
16 Gets a Connection instance, that will be used to
17 make the HTTP requests to the application
19 connectionUrl = 'http://%s:%s/' % (server, port)
21 conn = Connection(connectionUrl, 'v0')
25 def formatDictToJSONPayload(dictionary):
27 Converts a given python dict instance to a string
28 JSON payload that can be sent to a REST API.
32 for (key, val) in dictionary.items():
37 valStr = valStr.lower()
38 optionsList.append('"%s":%s' % (key, valStr))
40 jsonPayload += ','.join(optionsList)
46 class Connection(object):
49 Class that executes the HTTP requests to the application instance.
50 It handles creating the HTTP session and executing HTTP methods.
53 kHeaderContentType = 'content-type'
54 kContentJson = 'application/json'
56 def __init__(self, siteUrl, apiVersion):
57 self.httpSession = None
59 self.url = Connection.urljoin(siteUrl, 'api')
60 self.url = Connection.urljoin(self.url, apiVersion)
62 def _getHttpSession(self):
64 This is a lazy initializer for the HTTP session.
65 It does not need to be active until it is required.
68 if self.httpSession is None:
69 self.httpSession = requests.Session()
70 return self.httpSession
73 def urljoin(cls, base, end):
74 """ Join two URLs. If the second URL is absolute, the base is ignored.
76 Use this instead of urlparse.urljoin directly so that we can customize
77 its behavior if necessary.
78 Currently differs in that it
80 1. appends a / to base if not present.
81 2. casts end to a str as a convenience
84 if base and not base.endswith('/'):
86 return urljoin(base, str(end))
88 def httpRequest(self, method, url='', data='', params={}, headers={}):
90 Method for making a HTTP request.
91 The method type (GET, POST, PATCH, DELETE) will be sent as a parameter.
92 Along with the url and request data. The HTTP response is returned
95 headers[Connection.kHeaderContentType] = Connection.kContentJson
97 absUrl = Connection.urljoin(self.url, url)
98 result = self._getHttpSession().request(method,
105 def httpGet(self, url='', data='', params={}, headers={}):
107 Method for calling HTTP GET.
108 This will return a WebObject that has the fields returned
109 in JSON format by the GET operation.
112 reply = self.httpRequest('GET', url, data, params, headers)
113 return _WebObject(reply.json())
115 def httpPost(self, url='', data='', params={}, headers={}):
117 Method for calling HTTP POST. Will return the HTTP reply.
120 return self.httpRequest('POST', url, data, params, headers)
122 def httpPatch(self, url='', data='', params={}, headers={}):
124 Method for calling HTTP PATCH. Will return the HTTP reply.
127 return self.httpRequest('PATCH', url, data, params, headers)
129 def httpDelete(self, url='', data='', params={}, headers={}):
131 Method for calling HTTP DELETE. Will return the HTTP reply.
134 return self.httpRequest('DELETE', url, data, params, headers)
137 def _WebObject(value):
139 Method used for creating a wrapper object corresponding to the JSON string
140 received on a GET request.
143 if isinstance(value, dict):
144 result = WebObject(**value)
145 elif isinstance(value, list):
146 result = WebList(entries=value)
155 Using this class a JSON list will be transformed
156 in a list of WebObject instances.
159 def __init__(self, entries=[]):
161 Create a WebList from a list of items that
162 are processed by the _WebObject function
166 self.append(_WebObject(item))
169 class WebObject(object):
172 A WebObject instance will have its fields set to correspond to
173 the JSON format received on a GET request.
176 def __init__(self, **entries):
178 Create a WebObject instance by providing a dict having a
179 property - value structure.
182 self.jsonOptions = {}
183 for (key, value) in entries.iteritems():
184 webObj = _WebObject(value)
185 self.jsonOptions[key] = webObj
186 self.__dict__[key] = webObj
188 def getOptions(self):
190 Get the JSON dictionary which represents the WebObject Instance
193 return self.jsonOptions