def _print_response(self, result, response, **args): if result: if 'raw_response' in args and args['raw_response']: if 'stdout_redir' in args and args['stdout_redir'] != None: args['file'].write(response) args['file'].close() else: sys.stdout.write(response) else: if response != None: if 'stdout_redir' in args and args['stdout_redir'] != None: args['file'].write(dbg.obj2str(response, color = False)) args['file'].close() else: if 'color' in args: dbg.pretty_print(response, color = args['color']) else: dbg.pretty_print(response, color = False) #sys.stdout.write('\n') else: sys.stderr.write('! ' + response + '\n') if 'data' in args: if 'color' in args: dbg.pretty_print(args['data'], color = args['color'], stream = sys.stderr) else: dbg.pretty_print(args['data'], color = False, stream = sys.stderr)
def send_report(self, to, bcc = None): import time # generate the body body = [ 'Exception Report', time.strftime("%Y-%m-%d %H:%M:%S"), '------------------------------', self.message, ] if self.data != None: body.push('\nData\n----') body.push(dbg.obj2str(self.data)) body = body.join('\n') # send mail if type(to) == type(''): self.send_mail(to, body) elif type(to) == type([]): for email in to: self.send_mail(to, body)
def _print_response(self, success, response, status=None, **args): if success: if response is not None: if 'stdout_redir' in args and args['stdout_redir'] is not None: #response = json.dumps( # response, # ensure_ascii=True, # sort_keys=True, # indent=4 #) args['file'].write(dbg.obj2str(response, color=False)) args['file'].close() else: if isinstance(response, basestring): if args.get('formatted'): chars_to_print = min(len(response), 256) sys.stderr.write('# %d/%d chars%s\n' % ( chars_to_print, len(response), ( ", use --raw|-r to see full output" if chars_to_print < len(response) else "" ) )) print response[0:chars_to_print] else: print response else: if args.get('formatted'): dbg.pretty_print( response, color=args.get('color'), invert_color=args.get('invert_color') ) else: print json.dumps(response, indent=4, sort_keys=True) else: if isinstance(response, basestring): if args['formatted']: chars_to_print = min(len(response), 256) sys.stderr.write('! %s (%d/%d chars)\n:%s\n' % ( status, chars_to_print, len(response), response[0:chars_to_print] )) else: sys.stderr.write('! %s:\n%s\n' % ( status, response )) else: sys.stderr.write('! %s:\n' % (status)) if args.get('formatted'): dbg.pretty_print( response, color=args.get('color'), invert_color=args.get('invert_color') ) else: print json.dumps(response, indent=4, sort_keys=True)
def __repr__(self): str = self.message if self.data != None: str = '\n'.join([str, dbg.obj2str(self.data)]) return str
def run(self, api, args = (), raw_response = False, full_response = False, get = None, post = None, files = None): # check and prep the data if api == '': raise Exception("Invalid service API: '%s'." %api) api = urllib.quote(api) curl = pycurl.Curl() data = [ ('OMEGA_ENCODING', (curl.FORM_CONTENTS, 'json')), ('OMEGA_API_PARAMS', (curl.FORM_CONTENTS, self.encode(args))) ] if self._credentials: data.append(('OMEGA_CREDENTIALS', (curl.FORM_CONTENTS, self.encode(self._credentials)))) # include any extra post data if post: (name, value) = post.split('=', 1) data.append((name, (curl.FORM_CONTENTS, value))) if files: # add in our files to the data for name in files: data.append((name, (curl.FORM_FILE, files[name]))) # figure our our URL and get args url = self._url if self._use_https: url = ''.join(('https://', self._hostname)) else: url = ''.join(('http://', self._hostname)) url = '/'.join((':'.join((url, str(self._port))), self._folder)) url = '/'.join((url, api)) url = re.sub(r'/+', '/', util.pretty_path(url)).replace(':/', '://', 1) if get: url = '?'.join((url, get)) # fire away curl.setopt(curl.URL, url) curl.setopt(curl.POST, 1) curl.setopt(curl.USERAGENT, self._useragent) curl.setopt(curl.COOKIEFILE, self._cookie_file) curl.setopt(curl.COOKIEJAR, self._cookie_file) if self._use_https: curl.setopt(curl.SSL_VERIFYPEER, 0) # TODO: don't always assume curl.setopt(curl.SSL_VERIFYHOST, 0) # TODO: don't always assume if data: curl.setopt(curl.HTTPPOST, data) else: curl.setopt(curl.POSTFIELDS, '&'.join(args)) response = StringIO.StringIO() curl.setopt(curl.WRITEFUNCTION, response.write) curl.perform() response = response.getvalue() http_code = curl.getinfo(curl.HTTP_CODE) content_type = curl.getinfo(curl.CONTENT_TYPE) or ""; if http_code < 200 or http_code >= 300: # see if we got json data back try: if content_type.startswith("application/json"): decoded = self.decode(response) if 'reason' in decoded: error = decoded['reason'] else: error = response else: error = response except: error = response raise Exception("Server returned HTTP code %s. Response:\n%s" % (str(http_code), str(error))) curl.close() if raw_response: return response else: # decode the response and check whether or not it was successful # TODO: check response encoding in header try: if content_type.startswith("application/json"): response = self.decode(response) else: return response except: raise Exception('Failed to decode API response.', response) # check to see if our API call was successful if 'result' in response and response['result'] == False: if 'reason' in response: if full_response: raise Exception('API "%s" failed.\n%s' % (urllib.unquote(api), dbg.obj2str(response))) else: raise Exception(response['reason']) else: raise Exception('API "%s" failed, but did not provide an explanation. Response: %s' % (api, response)) else: if full_response: return response else: if 'data' in response: return response['data'] else: return None
try: result = self.decode(response_data) except: result = {"result": False, "reason": response_data} if 'reason' in result: error = result['reason'] else: error = 'An unknown error has occurred.' else: result = response_data error = response_data if full_response: if raw_response: msg = response_data else: msg = dbg.obj2str(result) raise Exception('API "%s" failed (%d %s)\n%s' % (urllib.unquote(api), response.status, response.reason, msg)) else: if raw_response: msg = response_data else: msg = error raise Exception('API "%s" failed (%d %s)\n%s' % (api, response.status, response.reason, msg)) # return a raw response if needed; otherwise decode if JSON if not content_type.startswith("application/json"): return response_data try: result = self.decode(response_data) except: