def callAPI(self, apiServer, resourcePath, method, queryParams, postData, headerParams=None, returnType=str): if self.__debug and self.__logFilepath: stdOut = sys.stdout logFile = open(self.__logFilepath, 'a') sys.stdout = logFile url = apiServer + resourcePath headers = {} if self.headers: for param, value in self.headers.items(): headers[param] = value if headerParams: for param, value in headerParams.items(): headers[param] = value isFileUpload = False if not postData: headers['Content-type'] = 'text/html' elif isinstance(postData, FileStream): isFileUpload = True if postData.contentType: headers['Content-type'] = 'application/octet-stream' if postData.size: headers['Content-Length'] = str(postData.size) else: headers['Content-type'] = 'application/json' if self.cookie: headers['Cookie'] = self.cookie data = None if queryParams: # Need to remove None values, these should not be sent sentQueryParams = {} for param, value in queryParams.items(): if value != None: sentQueryParams[param] = value if sentQueryParams: url = url + '?' + urllib.parse.urlencode(sentQueryParams) if method in ['POST', 'PUT', 'DELETE']: if isFileUpload: data = postData.inputStream elif not postData: data = "" elif type(postData) not in [str, int, float, bool]: data = self.signer.signContent(json.dumps(self.sanitizeForSerialization(postData)), headers) else: data = self.signer.signContent(postData, headers) if self.__debug: http.client.HTTPConnection.debuglevel = 1 if data and not isFileUpload: data = data.encode('utf-8') request = MethodRequest(method=method, url=self.encodeURI(self.signer.signUrl(url)), headers=headers, data=data) try: # Make the request response = urllib.request.urlopen(request) if 'Set-Cookie' in response.headers: self.cookie = response.headers['Set-Cookie'] if response.code == 200 or response.code == 201 or response.code == 202: if returnType == FileStream: fs = FileStream.fromHttp(response) if self.__debug: print("\n", "< Response Body:\n", ">>>stream info: fileName=%s contentType=%s size=%s" % (fs.fileName, fs.contentType, fs.size), "\n", sep="") return fs if 'Transfer-Encoding' in response.headers or (fs.size != None and int(fs.size) > 0) else None else: encoding = response.headers.get_content_charset() if not encoding: encoding = 'iso-8859-1' string = response.read().decode(encoding) if self.__debug: print("\n", "< Response Body:\n", string, "\n", sep="") try: data = json.loads(string) except ValueError: # PUT requests don't return anything data = None return data elif response.code == 404: return None else: encoding = response.headers.get_content_charset() if not encoding: encoding = 'iso-8859-1' string = response.read().decode(encoding) try: msg = json.loads(string)['error_message'] except ValueError: msg = string raise ApiException(response.code, msg) except urllib.error.HTTPError as e: raise ApiException(e.code, e.msg) finally: if isFileUpload: try: postData.inputStream.close() except Exception as e: pass if self.__debug: http.client.HTTPConnection.debuglevel = 0 if self.__logFilepath: sys.stdout = stdOut logFile.close()
def setUp(self): # TODO mock http response response = {} response.closed = False self.fs = FileStream.fromHttp(response)
def callAPI(self, apiServer, resourcePath, method, queryParams, postData, headerParams=None, returnType=str): if self.__debug and self.__logFilepath: stdOut = sys.stdout logFile = open(self.__logFilepath, 'a') sys.stdout = logFile url = apiServer + resourcePath headers = {} if self.headers: for param, value in self.headers.iteritems(): headers[param] = value if headerParams: for param, value in headerParams.iteritems(): headers[param] = value isFileUpload = False if not postData: headers['Content-type'] = 'text/html' elif isinstance(postData, FileStream): isFileUpload = True if postData.contentType: headers['Content-type'] = postData.contentType if postData.size: headers['Content-Length'] = str(postData.size) else: headers['Content-type'] = 'application/json' if self.cookie: headers['Cookie'] = self.cookie data = None if queryParams: # Need to remove None values, these should not be sent sentQueryParams = {} for param, value in queryParams.items(): if value != None: sentQueryParams[param] = value if sentQueryParams: url = url + '?' + urllib.urlencode(sentQueryParams) if method in ['POST', 'PUT', 'DELETE']: if isFileUpload: data = postData.inputStream elif not postData: data = "" elif type(postData) not in [unicode, int, float, bool]: data = self.signer.signContent(json.dumps(self.sanitizeForSerialization(postData)), headers) else: data = self.signer.signContent(postData, headers) if self.__debug: handler = urllib2.HTTPSHandler(debuglevel=1) if url.lower().startswith('https') else urllib2.HTTPHandler(debuglevel=1) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) request = MethodRequest(method=method, url=self.encodeURI(self.signer.signUrl(url)), headers=headers, data=data) try: # Make the request response = urllib2.urlopen(request) if 'Set-Cookie' in response.headers: self.cookie = response.headers['Set-Cookie'] if response.code == 200 or response.code == 201 or response.code == 202: if returnType == FileStream: fs = FileStream.fromHttp(response) if self.__debug: print(">>>stream info: fileName=%s contentType=%s size=%s" % (fs.fileName, fs.contentType, fs.size)) return fs if 'Transfer-Encoding' in response.headers or (fs.size != None and int(fs.size) > 0) else None else: string = response.read() if self.__debug: print(string) try: data = json.loads(string) except ValueError: # PUT requests don't return anything data = None return data elif response.code == 404: return None else: string = response.read() try: msg = json.loads(string)['error_message'] except ValueError: msg = string raise ApiException(response.code, msg) except urllib2.HTTPError, e: raise ApiException(e.code, e.msg)