Python falcon.HTTPInternalServerError() Examples

The following are 25 code examples of falcon.HTTPInternalServerError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def on_get(self, req, resp, ical_key):
        """Access the oncall calendar identified by the key.

        The response is in ical format and this url is intended to be
        supplied to any calendar application that can subscribe to
        calendars from the internet.
        """
        try:
            path = self.base_url + '/api/v0/ical/' + ical_key
            if req.query_string:
                path += '?%s' % req.query_string
            result = self.oncall_client.get(path)
        except MaxRetryError as ex:
            logger.error(ex)
        else:
            if result.status_code == 200:
                resp.status = falcon.HTTP_200
                resp.content_type = result.headers['Content-Type']
                resp.body = result.content
                return
            elif 400 <= result.status_code <= 499:
                resp.status = falcon.HTTP_404
                return

        raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API') 
Example #2
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_get(self, req, resp):
        token = req.get_param('token', True)
        data = {}
        for key in self.data_keys:
            data[key] = req.get_param(key, True)

        if not self.validate_token(token, data):
            raise falcon.HTTPForbidden('Invalid token for these given values', '')

        endpoint = self.config['iris']['hook']['gmail_one_click']

        try:
            result = self.iclient.post(endpoint, data)
        except MaxRetryError:
            logger.exception('Hitting iris-api failed for gmail oneclick')
        else:
            if result.status == 204:
                resp.status = falcon.HTTP_204
                return
            else:
                logger.error('Unexpected status code from api %s for gmail oneclick', result.status)

        raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API') 
Example #3
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(self, req, resp):
        """
        Accept twilio POST that has message delivery status, and pass it
        to iris-api
        """

        try:
            re = self.iclient.post(self.endpoint, req.context['body'].decode('utf-8'), raw=True)
        except MaxRetryError:
            logger.exception('Failed posting data to iris-api')
            raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed')

        if re.status != 204:
            logger.error('Invalid response from API for delivery status update: %s', re.status)
            raise falcon.HTTPBadRequest('Likely bad params passed', 'Invalid response from API')

        resp.status = falcon.HTTP_204 
Example #4
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    if hasattr(ex, 'title') and "Failed data validation" in ex.title:
        JsonSchemaException(ex)
    message = "Unexpected error occurred: {}".format(ex)
    logger.error(message + "\nRequest: {}  Params: {}".format(req, params))

    if isinstance(ex, falcon.HTTPUnauthorized):
        raise ex

    if isinstance(ex, falcon.HTTPForbidden):
        raise ex

    stacktrace = traceback.format_exc()
    logger.error(stacktrace)

    raise falcon.HTTPInternalServerError(message) 
Example #5
Source File: resource.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def resource_try_catch_block(fun):
    def try_it(*args, **kwargs):
        try:
            return fun(*args, **kwargs)

        except falcon.HTTPError:
            raise

        except exceptions.DoesNotExistException:
            raise falcon.HTTPNotFound

        except exceptions.MultipleMetricsException as ex:
            raise falcon.HTTPConflict("MultipleMetrics", str(ex))

        except exceptions.AlreadyExistsException as ex:
            raise falcon.HTTPConflict(ex.__class__.__name__, str(ex))

        except exceptions.InvalidUpdateException as ex:
            raise HTTPUnprocessableEntityError(ex.__class__.__name__, str(ex))

        except exceptions.RepositoryException as ex:
            LOG.exception(ex)
            msg = " ".join(map(str, ex.args[0].args))
            raise falcon.HTTPInternalServerError('The repository was unable '
                                                 'to process your request',
                                                 msg)

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex))

    return try_it 
Example #6
Source File: alarming.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def send_event(self, message_queue, event_msg):
        try:
            message_queue.send_message(helpers.to_json(event_msg))
        except message_queue_exceptions.MessageQueueException as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError(
                'Message queue service unavailable'.encode('utf8'),
                str(ex).encode('utf8')) 
Example #7
Source File: metrics.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            super(DimensionValues, self).__init__()
            self._region = cfg.CONF.region
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable', str(ex)) 
Example #8
Source File: metrics.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            super(MetricsNames, self).__init__()
            self._region = cfg.CONF.region
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex)) 
Example #9
Source File: metrics.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            super(MetricsStatistics, self).__init__()
            self._region = cfg.CONF.region
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex)) 
Example #10
Source File: metrics.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            super(MetricsMeasurements, self).__init__()
            self._region = cfg.CONF.region
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex)) 
Example #11
Source File: metrics.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            super(Metrics, self).__init__()
            self._region = cfg.CONF.region
            self._message_queue = simport.load(cfg.CONF.messaging.driver)(
                'metrics')
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()
            self._batch_size = cfg.CONF.kafka.queue_buffering_max_messages

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex)) 
Example #12
Source File: swagger_server.py    From falsy with MIT License 5 votes vote down vote up
def process(self, req, resp):
        if req.method == 'OPTIONS':
            if self.cors_origin is not False:
                self.process_preflight_request(req, resp)
            response_body = '\n'

            response_body += 'nothing here\n\n'

            resp.body = response_body
            resp.status = falcon.HTTP_200
            return
        try:
            if self.cors_origin is not False:
                self.process_preflight_request(req, resp)
            self.dispatch(req, resp)
        except Exception as e:
            self.log.error_trace('process failed')
            error_type = type(e)
            error_map = {
                falcon.errors.HTTPNotFound: http_falcon_handler,
                falcon.errors.HTTPMissingParam: http_falcon_handler,
                falcon.errors.HTTPInvalidParam: http_falcon_handler,
                falcon.errors.HTTPInternalServerError: http_falcon_handler,
            }
            if self.custom_error_map:
                error_map.update(self.custom_error_map)

            error_func = error_map.get(error_type)
            if error_func:
                error_func(req, resp, e)
            else:
                default_error_handler(req, resp, e) 
Example #13
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def handler(ex, req, resp, params):
        message = "{} {} is not available".format(ex.name, ex.resource)
        logger.error(message)
        raise falcon.HTTPInternalServerError(message) 
Example #14
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def handler(ex, req, resp, params):
        logger.error(str(ex))
        raise falcon.HTTPInternalServerError(str(ex)) 
Example #15
Source File: errors_handling.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def form_response(self, message):
        if self.k8s_api_exception.status == 403:
            raise falcon.HTTPForbidden(message)
        elif 400 <= self.k8s_api_exception.status < 500:
            raise falcon.HTTPBadRequest(message)
        else:
            raise falcon.HTTPInternalServerError(message) 
Example #16
Source File: server.py    From spacy-api-docker with MIT License 5 votes vote down vote up
def on_get(self, req, resp):
        try:
            resp.body = json.dumps({
                "spacy": spacy.about.__version__
            }, sort_keys=True, indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPInternalServerError(
                'Version retrieval failed',
                '{}'.format(e)) 
Example #17
Source File: server.py    From spacy-api-docker with MIT License 5 votes vote down vote up
def on_get(self, req, resp):
        try:
            output = list(MODELS)
            resp.body = json.dumps(output, sort_keys=True, indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPInternalServerError(
                'Models retrieval failed',
                '{}'.format(e)) 
Example #18
Source File: exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def handle(ex, req, resp, params):
        raise falcon.HTTPInternalServerError(
            title=_("Internal Storage Error"),
            description=ex.message) 
Example #19
Source File: test_exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def test_StorageEngineError(self):
        e = exceptions.StorageEngineError(message='testing')
        self.assertRaises(falcon.HTTPInternalServerError,
                          e.handle, self.ex, self.mock_req, self.mock_req,
                          None) 
Example #20
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_post(self, req, resp):
        data = ujson.loads(req.context['body'].decode('utf-8'))
        data['username'] = req.context['user']
        result = self.iris.post('devices', data)
        if result.status == 400:
            raise falcon.HTTPBadRequest('Bad Request', '')
        elif result.status != 201:
            logger.error('Unknown response from API: %s: %s', result.status, result.data)
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
        resp.status = falcon.HTTP_201 
Example #21
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __call__(self, req, resp):
        path = self.base_url + '/v0/' + '/'.join(req.path.split('/')[4:])
        if req.query_string:
            path += '?%s' % req.query_string
        try:
            if req.method == 'POST':
                body = b''
                if req.context['body']:
                    body = req.context['body']
                result = self.iris_client.post(path, body)
            elif req.method == 'GET':
                result = self.iris_client.get(path)
            elif req.method == 'OPTIONS':
                return
            else:
                raise falcon.HTTPMethodNotAllowed(['GET', 'POST', 'PUT', 'DELETE'])
        except MaxRetryError as e:
            logger.error(e.reason)
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Max retry error, api unavailable')
        if result.status_code == 400:
            raise falcon.HTTPBadRequest('Bad Request', '')
        elif str(result.status_code)[0] != '2':
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
        else:
            resp.status = falcon.HTTP_200
            resp.content_type = result.headers['Content-Type']
            resp.body = result.content 
Example #22
Source File: swagger_server.py    From falsy with MIT License 4 votes vote down vote up
def dispatch(self, req, resp):
        base_before, base_after, base_excp, base_final = self.op_loader.load_base(self.specs)
        for uri_regex, spec in self.specs.items():
            # try:
            route_signature = '/' + req.method.lower() + req.relative_uri
            if route_signature.find('?') > 0:
                route_signature = route_signature[:route_signature.find('?')]
            if type(uri_regex) == str:
                continue
            spec['route_signature'] = route_signature
            req.spec = copy.deepcopy(spec)

            match = uri_regex.match(route_signature)
            if match:
                handler, params, before, after, excp, final, mode = self.op_loader.load(req=req, spec=spec,
                                                                                        matched_uri=match)
                handler_return = None
                try:
                    if base_before:
                        base_before(req=req, resp=resp, **params)
                    if before:
                        before(req=req, resp=resp, **params)
                    if mode == 'raw':
                        handler_return = handler(req=req, resp=resp)
                    else:
                        if mode == 'more':
                            handler_return = handler(req=req, resp=resp, **params)
                        else:
                            handler_return = handler(**params)

                        content_type = self.produces(spec.get('produces'), self.specs.get('produces'))
                        self.process_response(req, resp, handler_return, content_type)
                    if after:
                        after(req=req, resp=resp, response=handler_return, **params)
                    if base_after:
                        base_after(req=req, resp=resp, **params)

                except Exception as e:
                    throw_out = True
                    if base_excp is not None:
                        throw_out = base_excp(req=req, resp=resp, error=e)
                    if excp is not None:
                        throw_out = excp(req=req, resp=resp, error=e)
                    if throw_out:
                        raise e
                finally:
                    if final:
                        final(req=req, resp=resp, response=handler_return, **params)
                    if base_final:
                        base_final(req=req, resp=resp, **params)
                return
            # except falcon.HTTPInvalidParam as e:
            #     self.log.error_trace("http invalid param: {}".format(e))
            #     raise e
            # except Exception as e:
            #     self.log.error_trace("process error: {}".format(e))
            #     raise falcon.HTTPInternalServerError(title=str(type(e)), description=str(e))
        self.log.info("url does not match any route signature or match error: {}".format(route_signature))
        raise falcon.HTTPNotFound() 
Example #23
Source File: eval.py    From snekbox with MIT License 4 votes vote down vote up
def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
        """
        Evaluate Python code and return stdout, stderr, and the return code.

        The return codes mostly resemble those of a Unix shell. Some noteworthy cases:

        - None
            The NsJail process failed to launch
        - 137 (SIGKILL)
            Typically because NsJail killed the Python process due to time or memory constraints
        - 255
            NsJail encountered a fatal error

        Request body:

        >>> {
        ...     "input": "print(1 + 1)"
        ... }

        Response format:

        >>> {
        ...     "stdout": "2\\n",
        ...     "returncode": 0
        ... }

        Status codes:

        - 200
            Successful evaluation; not indicative that the input code itself works
        - 400
           Input's JSON schema is invalid
        - 415
            Unsupported content type; only application/JSON is supported
        """
        code = req.media["input"]

        try:
            result = self.nsjail.python3(code)
        except Exception:
            log.exception("An exception occurred while trying to process the request")
            raise falcon.HTTPInternalServerError

        resp.media = {
            "stdout": result.stdout,
            "returncode": result.returncode
        } 
Example #24
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def on_post(self, req, resp):
        """
        Accept slack's message from interactive buttons
        """
        try:
            req.context['body'] = req.context['body'].decode('utf-8')
            form_post = falcon.uri.parse_query_string(req.context['body'])
            payload = ujson.loads(form_post['payload'])
            if not self.valid_token(payload['token']):
                logger.error('Invalid token sent in the request.')
                raise falcon.HTTPUnauthorized('Access denied',
                                              'Not a valid auth token')
            try:
                msg_id = int(payload['callback_id'])
            except KeyError as e:
                logger.error(e)
                logger.error('callback_id not found in the json payload.')
                raise falcon.HTTPBadRequest('Bad Request', 'Callback id not found')
            except ValueError as e:
                logger.error(e)
                logger.error('Callback ID not an integer: %s', payload['callback_id'])
                raise falcon.HTTPBadRequest('Bad Request', 'Callback id must be int')
            data = {'msg_id': msg_id,
                    'source': payload['user']['name'],
                    'content': payload['actions'][0]['name']}
            endpoint = self.config['iris']['hook']['slack']
            try:
                result = self.iclient.post(endpoint, data)
            except MaxRetryError as e:
                logger.error(e.reason)
                return
            if result.status == 400:
                raise falcon.HTTPBadRequest('Bad Request', '')
            elif result.status != 200:
                raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
            else:
                content = process_api_response(result.data)
                self.return_slack_message(resp, content)
            return
        except Exception:
            logger.exception('Unable to read payload from slack. Our post body: %s', req.context['body'])
            raise falcon.HTTPBadRequest('Bad Request', 'Unable to read the payload from slack') 
Example #25
Source File: builder.py    From certidude with MIT License 4 votes vote down vote up
def on_get(self, req, resp, profile, suggested_filename):
        router = [j[0] for j in authority.list_signed(
            common_name=config.cp2.get(profile, "router"))][0]
        subnets = set([ip_network(j) for j in config.cp2.get(profile, "subnets").replace(",", " ").split(" ")])
        model = config.cp2.get(profile, "model")
        build_script_path = config.cp2.get(profile, "command")
        overlay_path = config.cp2.get(profile, "overlay")
        site_script_path = config.cp2.get(profile, "script")
        suffix = config.cp2.get(profile, "filename")

        build = "/var/lib/certidude/builder/" + profile
        log_path = build + "/build.log"
        if not os.path.exists(build + "/overlay/etc/uci-defaults"):
            os.makedirs(build + "/overlay/etc/uci-defaults")
        os.system("rsync -av " + overlay_path + "/ " + build + "/overlay/")

        if site_script_path:
            template = Template(open(site_script_path).read())
            with open(build + "/overlay/etc/uci-defaults/99-site-config", "w") as fh:
                fh.write(template.render(authority_name=const.FQDN))

        proc = subprocess.Popen(("/bin/bash", build_script_path),
            stdout=open(log_path, "w"), stderr=subprocess.STDOUT,
            close_fds=True, shell=False,
            cwd=os.path.dirname(os.path.realpath(build_script_path)),
            env={"PROFILE": model, "PATH":"/usr/sbin:/usr/bin:/sbin:/bin",
                "ROUTER": router,
                "IKE": config.cp2.get(profile, "ike"),
                "ESP": config.cp2.get(profile, "esp"),
                "SUBNETS": ",".join(str(j) for j in subnets),
                "AUTHORITY_CERTIFICATE_ALGORITHM": authority.public_key.algorithm,
                "AUTHORITY_CERTIFICATE_DISTINGUISHED_NAME": cert_to_dn(authority.certificate),
                "BUILD":build, "OVERLAY":build + "/overlay/"},
            startupinfo=None, creationflags=0)
        proc.communicate()
        if proc.returncode:
            logger.info("Build script finished with non-zero exitcode, see %s for more information" % log_path)
            raise falcon.HTTPInternalServerError("Build script finished with non-zero exitcode")

        for dname in os.listdir(build):
            if dname.startswith("openwrt-imagebuilder-") and ".tar." not in dname:
                subdir = os.path.join(build, dname, "bin", "targets")
                for root, dirs, files in os.walk(subdir):
                    for filename in files:
                        if filename.endswith(suffix):
                            path = os.path.join(root, filename)
                            click.echo("Serving: %s" % path)
                            resp.body = open(path, "rb").read()
                            resp.set_header("Content-Disposition", ("attachment; filename=%s" % suggested_filename))
                            return
                raise falcon.HTTPNotFound(description="Couldn't find file ending with '%s' in directory %s" % (suffix, subdir))
        raise falcon.HTTPNotFound(description="Failed to find image builder directory in %s" % build)