def __init__(self, exc_info): e = exc_info[1] log.error(repr(e)) body_template = "<b>${explanation}</b>\n<hr/>\n" cls = e.__class__.__name__ if not e.args: self.explanation = "%s" % cls else: self.explanation = "%s: %s" % (cls, e.args[0]) if log.getEffectiveLevel() > logging.DEBUG: # no debug detail = production_error_msg % \ rnaseqlyze.admin_email body_template += "${detail}" else: # debug detail = '' if isinstance(e, DBAPIError): detail += dberror_msg import traceback detail += '%s\n\nStack trace:\n' % e detail += ''.join(traceback.format_tb(exc_info[2])) log.debug(detail) body_template += "<pre>\n${detail}</pre>" HTTPError.__init__(self, detail, body_template=body_template)
def json_error(status_code=400, status_message="error", errors=()): """Construct a cornice-format JSON error response.""" err = HTTPError() err.content_type = "application/json" err.status_code = status_code err.body = json.dumps({ "status": status_message, "errors": errors, }) return err
def __init__(self, exc_info): import traceback err = exc_info[1] message = [ self.title, " - ", brep(err), '\n\nStack trace:\n' ] + \ traceback.format_tb(exc_info[2]) log.error(brep(err)) log.debug(''.join(message)) HTTPError.__init__(self, app_iter=message, content_type='text/plain')
def api_search_json(self): """ View code Performs search request to the DDB API. Returns the result in JSON Requires: - HTTP-GET request - HTTP-GET parameter format set to 'json' Returns: - JSON (pretty printed) Raises: - HttpError """ try: params = {} params['query'] = self.request.GET['query'] bbox = self.request.GET['bbox'].split(",") bbox = dict(min_y=bbox[1], min_x=bbox[0], max_y=bbox[3], max_x=bbox[2]) resolution = float( self.request.GET['resolution']) #611.4962261962891 radius = int(self.request.GET.get('radius', 40)) request = self._api_search(**params) if request and request.ok: jresult = request.json()["results"][0]["docs"] dict_of_ids = {} for d in jresult: dict_of_ids[d['id']] = d['title'] clusters = self._cluster(bbox=bbox, resolution=resolution, radius=radius, ids=dict_of_ids) result = dict(type="FeatureCollection", features=[c.__json__() for c in clusters]) return result else: raise HTTPError("Request failed") except Exception, e: raise HTTPError("Request failed")
def api_get_item_html(self): """ View code Performs item request to the DDB API. Returns the result as HTML Requires: - HTTP-GET request - HTTP-GET parameter format set to 'html' Returns: - HTML Raises: - HttpError """ if self.request.matched_route.name == 'api_get_item_ajax': self.request.matchdict['itemid'] = self.request.GET.getone( 'itemid') request = self._api_get_item() if request and request.ok: jcontent = request.json() item = jcontent['view']['item'] item['id'] = self.request.matchdict['itemid'] if jcontent['preview']['thumbnail']: thumbnail = jcontent['preview']['thumbnail'].get('@href', None) else: thumbnail = None return dict(item=item, thumbnail=thumbnail) else: raise HTTPError("Request failed")
def mystripe(request): stripe.api_key = request.registry.settings['stripe_key'] data = request.json_body try: event = stripe.Event.construct_from(data, stripe.api_key) except ValueError as e: print(f"Invalid payload: {e}") return HTTPError(detail='Invalid payload') if event.type == 'payment_intent.succeeded': payment_intent = event.data.object decimalplace = len(str(payment_intent.amount)) - 2 # F*****g Stripe. amount = float( f'{str(payment_intent.amount)[:decimalplace]}.{str(payment_intent.amount)[decimalplace:]}' ) if payment_intent.currency == 'usd': numsnickers = str(round(amount / 1.48)) elif payment_intent.currency == 'eur': numsnickers = str(round(amount / 1.25)) elif payment_intent.currency == 'gbp': numsnickers = str(round(amount / 0.65)) else: numsnickers = 'an unknown amount of' print( f'[\x0315Stripe\x03] A donation of \x0315{str(amount)}\x03 {payment_intent.currency.upper()} ' f'was made. This equals about {numsnickers} snickers!') send( f'#{request.registry.settings["stripe_channel"]}', f'[\x0315Stripe\x03] A donation of \x0315{str(amount)}\x03 {payment_intent.currency.upper()} ' f'was made. This equals about {numsnickers} snickers!', 'No!', request)
def download(request, url): downloads_path = request.registry.settings['convertit.downloads_path'] message = "Sorry, there was an error fetching the document. Reason: %s" try: downloaded_filepath = download_file(url, downloads_path) return downloaded_filepath except ValueError as e: raise HTTPBadRequest(message % str(e)) except urllib2.HTTPError as e: raise HTTPError(message % str(e), status_int=e.getcode()) except urllib2.URLError as e: raise HTTPBadRequest(message % str(e))
def download(request, url): downloads_path = request.registry.settings['convertit.downloads_path'] message = "Sorry, there was an error fetching the document. Reason: %s" try: downloaded_filepath = download_file(url, downloads_path, headers=request.headers) return downloaded_filepath except ValueError as e: log.error(message % str(e)) raise HTTPBadRequest(body=message % str(e), content_type='text/plain') except urllib2.HTTPError as e: log.error(message % str(e)) raise HTTPError(body=message % str(e), status_int=e.getcode(), content_type='text/plain') except urllib2.URLError as e: log.error(message % str(e)) raise HTTPBadRequest(body=message % str(e), content_type='text/plain')
def inquire_images(document): patent = decode_patent_number(document) if not patent: raise HTTPBadRequest('{0} is not a valid patent number'.format(document)) image_representative(patent) # v1: docdb if patent.kind: ops_patent = patent['country'] + '.' + patent['number'] + '.' + patent['kind'] url_image_inquiry_tpl = '{baseuri}/published-data/publication/docdb/images' # v2: epodoc else: ops_patent = patent['country'] + patent['number'] url_image_inquiry_tpl = '{baseuri}/published-data/publication/epodoc/images' url_image_inquiry = url_image_inquiry_tpl.format(baseuri=OPS_API_URI) log.debug('Inquire image information via {url}'.format(url=url_image_inquiry)) error_msg_access = 'No image information for document={0}'.format(document) error_msg_process = 'Error while processing image information for document={0}'.format(document) # Inquire image metadata from OPS. ops = get_ops_client() response = ops._make_request(url_image_inquiry, ops_patent) # Evaluate response. if response.status_code != 200: if response.status_code == 404: log.warn(error_msg_access) error = HTTPNotFound(error_msg_access) error.status_code = response.status_code else: log.error(error_msg_access + '\n' + str(response) + '\n' + str(response.content)) error = HTTPError(error_msg_access) error.status_code = response.status_code # TODO: respond with proper json error raise error try: data = response.json() except JSONDecodeError as ex: # TODO: respond with proper json error error_msg_process += ': {0}'.format(str(ex)) log.error(error_msg_process) error = HTTPError(error_msg_process) error.status_code = 500 raise error result = data['ops:world-patent-data']['ops:document-inquiry']['ops:inquiry-result'] info = {} for node in to_list(result['ops:document-instance']): # Suppress correction pages of amendments like US2010252183A1. if is_amendment_only(node): continue # Aggregate nodes into map, using the '@desc' attribute as key key = node['@desc'] info[key] = node # Enrich image inquiry information. Compute image information for carousel widget. enrich_image_inquiry_info(info) #log.info('Image info: %s', info) return info
def test_ignore_if_error_response(self, request_, mocker): from pyramid.httpexceptions import HTTPError add_to = mocker.patch('adhocracy_core.activity.add_to_auditlog') self.call_fut(request_, HTTPError()) assert not add_to.called