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
79 1. appends a / to base if not present.
80 2. casts end to a str as a convenience
83 if base and not base.endswith('/'):
85 return urljoin(base, str(end))
87 def httpRequest(self, method, url='', data='', params={}, headers={}):
89 Method for making a HTTP request.
90 The method type (GET, POST, PATCH, DELETE) will be sent as a parameter.
91 Along with the url and request data. The HTTP response is returned
94 headers[Connection.kHeaderContentType] = Connection.kContentJson
96 absUrl = Connection.urljoin(self.url, url)
97 result = self._getHttpSession().request(method,
104 def httpGet(self, url='', data='', params={}, headers={}):
106 Method for calling HTTP GET.
107 This will return a WebObject that has the fields returned
108 in JSON format by the GET operation.
111 reply = self.httpRequest('GET', url, data, params, headers)
112 return _WebObject(reply.json())
114 def httpPost(self, url='', data='', params={}, headers={}):
116 Method for calling HTTP POST. Will return the HTTP reply.
119 return self.httpRequest('POST', url, data, params, headers)
121 def httpPatch(self, url='', data='', params={}, headers={}):
123 Method for calling HTTP PATCH. Will return the HTTP reply.
126 return self.httpRequest('PATCH', url, data, params, headers)
128 def httpDelete(self, url='', data='', params={}, headers={}):
130 Method for calling HTTP DELETE. Will return the HTTP reply.
133 return self.httpRequest('DELETE', url, data, params, headers)
136 def _WebObject(value):
138 Method used for creating a wrapper object corresponding to the JSON string
139 received on a GET request.
142 if isinstance(value, dict):
143 result = WebObject(**value)
144 elif isinstance(value, list):
145 result = WebList(entries=value)
154 Using this class a JSON list will be transformed
155 in a list of WebObject instances.
158 def __init__(self, entries=[]):
160 Create a WebList from a list of items that
161 are processed by the _WebObject function
165 self.append(_WebObject(item))
168 class WebObject(object):
171 A WebObject instance will have its fields set to correspond to
172 the JSON format received on a GET request.
175 def __init__(self, **entries):
177 Create a WebObject instance by providing a dict having a
178 property - value structure.
181 self.jsonOptions = {}
182 for (key, value) in entries.iteritems():
183 webObj = _WebObject(value)
184 self.jsonOptions[key] = webObj
185 self.__dict__[key] = webObj
187 def getOptions(self):
189 Get the JSON dictionary which represents the WebObject Instance
192 return self.jsonOptions