Python falcon 模块,HTTPInternalServerError() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用falcon.HTTPInternalServerError()

项目:kge-server    作者:vfrico    | 项目源码 | 文件源码
def on_delete(self, req, resp, dataset_id, **kwargs):
        """Delete a dataset from the service

        This method will delete the entry from the datbase and will also
        delete the entire datasets generated by them on filesystem.

        :param integer dataset_id: Unique ID of dataset
        :returns: Nothing if operation was successful
        :rtype: 204 NO CONTENT
        """
        try:
            delete_task = async_tasks.delete_dataset_by_id(dataset_id)
        except LookupError:
            raise falcon.HTTPNotFound(description="Couldn't locate dataset")
        except OSError as err:
            raise falcon.HTTPInternalServerError(description=str(err))
        else:
            resp.status = falcon.HTTP_204
项目:Cuppa    作者:flipkart-incubator    | 项目源码 | 文件源码
def test_on_get(self):
        time.sleep(1)
        req = None
        resp = falcon.Response()
        resp.status = None
        resp.body = None
        self.elb_resource.on_get(req, resp)
        response_body = json.loads(resp.body)
        self.assertEquals(response_body['capacity'], 100)
        self.assertEquals(response_body['requests'], 1)
        self.assertGreaterEqual(response_body['uptime'], 1)
        self.assertEquals(resp.status, falcon.HTTP_200)

        self.load_balancer.check_if_model_to_workers_map_is_empty = MagicMock(return_value = True)

        resp_1 = falcon.Response()
        resp_1.status = None
        resp_1.body = None

        self.assertRaises(falcon.HTTPInternalServerError, lambda : self.elb_resource.on_get(req, resp_1))
项目:Cuppa    作者:flipkart-incubator    | 项目源码 | 文件源码
def on_get(self, req, resp):
        """
        Handles GET requests for ELB HealthCheck Resource
        :param req:
        :param resp:
        :return:
        """
        uptime = int(time.time()) - self.start_time

        if self.load_balancer.check_if_model_to_workers_map_is_empty():
            resp.status = falcon.HTTP_500
            resp.body = "Model To Workers Map is Empty"
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Model To Workers Map is Empty! ')

        resp.status = falcon.HTTP_200

        # TODO requests and capacity have to be calculated. They are hardcoded for now

        resp.body = json.dumps({'uptime':uptime, 'requests': 1, 'capacity': 100})
项目:Cuppa    作者:flipkart-incubator    | 项目源码 | 文件源码
def on_post(self, req, resp):
        payload = json.loads(req.stream.read())
        pi = PredictionInput()
        if ('url' in payload.keys()) and ('modelId' in payload.keys()):
            pi.url = payload['url']
            pi.model_id = payload['modelId']
        else:
            resp.status = falcon.HTTP_400
            raise falcon.HTTPBadRequest("Bad Request", "Url and(or) modelId missing in the payload")

        po = self.caffe_worker_client.predict(pi)

        if po.bo.status == 'Success':
            resp.status = falcon.HTTP_200
            resp.body = (str(po.values))
        elif po.bo.status == 'Failure':
            resp.body = json.dumps({'status': 'Failure', 'message' : 'Error occurred'})
            resp.status = falcon.HTTP_500
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Predict failed! ')
项目:iris-relay    作者:linkedin    | 项目源码 | 文件源码
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')
项目:iris-relay    作者:linkedin    | 项目源码 | 文件源码
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'], raw=True)
        except MaxRetryError:
            logger.exception('Failed posting data to iris-api')
            raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed')

        if re.status is not 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
项目:graph    作者:noxern    | 项目源码 | 文件源码
def handle_exception(exception):
    logging.exception('An exception with the following traceback occurred:')
    raise falcon.HTTPInternalServerError('error', str(exception))
项目:CAL    作者:HPCC-Cloud-Computing    | 项目源码 | 文件源码
def _error_handler(self, exc, request, response, params):
        """Handler error"""
        if isinstance(exc, falcon.HTTPError):
            raise exc
        LOG.exception(exc)
        raise falcon.HTTPInternalServerError('Internal server error',
                                             six.text_type(exc))
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def _post_validate(self, documents):
        # Perform schema validation post-rendering to ensure that rendering
        # and substitution didn't break anything.
        doc_validator = document_validation.DocumentValidation(documents)
        try:
            doc_validator.validate_all()
        except (errors.InvalidDocumentFormat,
                errors.InvalidDocumentSchema) as e:
            LOG.error('Failed to post-validate rendered documents.')
            LOG.exception(e.format_message())
            raise falcon.HTTPInternalServerError(
                description=e.format_message())
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def _create_revision_documents(self, bucket_name, documents,
                                   validations):
        try:
            created_documents = db_api.documents_create(
                bucket_name, documents, validations=validations)
        except (deckhand_errors.DocumentExists,
                deckhand_errors.SingletonDocumentConflict) as e:
            raise falcon.HTTPConflict(description=e.format_message())
        except Exception as e:
            raise falcon.HTTPInternalServerError(description=six.text_type(e))

        return created_documents
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_misc(self, client):
        self._misc_test(client, falcon.HTTPBadRequest, falcon.HTTP_400)
        self._misc_test(client, falcon.HTTPNotAcceptable, falcon.HTTP_406,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPConflict, falcon.HTTP_409)
        self._misc_test(client, falcon.HTTPPreconditionFailed, falcon.HTTP_412)
        self._misc_test(client, falcon.HTTPUnsupportedMediaType, falcon.HTTP_415,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPUnprocessableEntity, falcon.HTTP_422)
        self._misc_test(client, falcon.HTTPUnavailableForLegalReasons, falcon.HTTP_451,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPInternalServerError, falcon.HTTP_500)
        self._misc_test(client, falcon.HTTPBadGateway, falcon.HTTP_502)
项目:gold-digger    作者:business-factory    | 项目源码 | 文件源码
def on_get(self, req, resp):
        from_currency = req.get_param("from", required=True)
        to_currency = req.get_param("to", required=True)
        date_of_exchange = req.get_param_as_date("date")
        date_of_exchange = date_of_exchange if date_of_exchange else date.today()

        invalid_currencies = [currency for currency in (from_currency, to_currency) if currency not in SUPPORTED_CURRENCIES]
        if invalid_currencies:
            raise falcon.HTTPInvalidParam("Invalid currency", " and ".join(invalid_currencies))

        exchange_rate = None
        try:
            exchange_rate = self.container.exchange_rate_manager.get_exchange_rate_by_date(date_of_exchange, from_currency, to_currency)
        except DatabaseError:
            self.container.db_session.rollback()
            self.container.logger.exception("Database error occurred. Rollback session to allow reconnect to the DB on next request.")
        except Exception:
            self.container.logger.exception("Unexpected exception while rate request %s->%s (%s)", from_currency, to_currency, date_of_exchange)

        if not exchange_rate:
            self.container.logger.error("Exchange rate not found: rate %s %s->%s", date_of_exchange, from_currency, to_currency)
            raise falcon.HTTPInternalServerError("Exchange rate not found", "Exchange rate not found")

        self.container.logger.info("GET rate %s %s->%s %s", date_of_exchange, from_currency, to_currency, exchange_rate)

        resp.status = falcon.HTTP_200
        resp.body = json.dumps(
            {
                "date": date_of_exchange.strftime(format="%Y-%m-%d"),
                "from_currency": from_currency,
                "to_currency": to_currency,
                "exchange_rate": str(exchange_rate)
            }
        )
项目:gold-digger    作者:business-factory    | 项目源码 | 文件源码
def on_get(self, req, resp):
        from_currency = req.get_param("from", required=True)
        to_currency = req.get_param("to", required=True)
        start_date = req.get_param_as_date("start_date", required=True)
        end_date = req.get_param_as_date("end_date", required=True)

        invalid_currencies = [currency for currency in (from_currency, to_currency) if currency not in SUPPORTED_CURRENCIES]
        if invalid_currencies:
            raise falcon.HTTPInvalidParam("Invalid currency", " and ".join(invalid_currencies))

        exchange_rate = None
        try:
            if start_date == end_date:
                exchange_rate = self.container.exchange_rate_manager.get_exchange_rate_by_date(start_date, from_currency, to_currency)
            else:
                exchange_rate = self.container.exchange_rate_manager.get_average_exchange_rate_by_dates(start_date, end_date, from_currency, to_currency)
        except DatabaseError:
            self.container.db_session.rollback()
            self.container.logger.exception("Database error occurred. Rollback session to allow reconnect to the DB on next request.")
        except Exception:
            self.container.logger.exception("Unexpected exception while range request %s->%s (%s - %s)", from_currency, to_currency, start_date, end_date)

        if not exchange_rate:
            self.container.logger.error("Exchange rate not found: range %s/%s %s->%s", start_date, end_date, from_currency, to_currency)
            raise falcon.HTTPInternalServerError("Exchange rate not found", "Exchange rate not found")

        self.container.logger.info("GET range %s/%s %s->%s %s", start_date, end_date, from_currency, to_currency, exchange_rate)

        resp.status = falcon.HTTP_200
        resp.body = json.dumps(
            {
                "start_date": start_date.strftime(format="%Y-%m-%d"),
                "end_date": end_date.strftime(format="%Y-%m-%d"),
                "from_currency": from_currency,
                "to_currency": to_currency,
                "exchange_rate": str(exchange_rate)
            }
        )
项目:kge-server    作者:vfrico    | 项目源码 | 文件源码
def on_put(self, req, resp, dataset_id, **kwargs):
        """Change the description of choosen dataset

        :param HTTPUserDatasetDTO dataset_info: Object with description param
        :param integer dataset_id: Unique ID of dataset
        :returns: The dataset with changed values
        :rtype: DatasetDTO
        """
        dataset_info = HTTPUserDatasetDTO()
        try:
            dataset_info.load(kwargs["dataset_info"])
        except KeyError:
            pass

        dataset_dao = data_access.DatasetDAO()
        if dataset_info.description is not None:
            res, err = dataset_dao.set_description(
                dataset_id, dataset_info.description)
            if res is None:
                raise falcon.HTTPInternalServerError(
                    title="Server Error",
                    description="Unable to process description param")

        resource, err = dataset_dao.get_dataset_by_id(dataset_id)
        response = {
            "dataset": resource.to_dict(),
        }
        resp.body = json.dumps(response)
        resp.content_type = 'application/json'
        resp.status = falcon.HTTP_200
项目:kge-server    作者:vfrico    | 项目源码 | 文件源码
def on_post(self, req, resp, dataset_info, **kwargs):
        """Create a new dataset on the service

        This method will create a new empty dataset, and returns a 201 CREATED
        with Location header filled with the URI of new dataset.

        :param HTTPUserDatasetDTO dataset_info: HTTP Client dataset information
        :query int dataset_type: The dataset type (optional)
        :returns: Location header with new path to dataset object
        """
        dao = data_access.DatasetDAO()
        # Get dataset type
        dts_type = req.get_param_as_int("dataset_type")

        dataset_type = dao.get_dataset_types()[dts_type]["class"]
        id_dts, err = dao.insert_empty_dataset(
            dataset_type, name=dataset_info.name,
            description=dataset_info.description)

        if id_dts is None and err[0] == 409:
            raise falcon.HTTPConflict(
                title="The dataset name is already used", description=err[1])
        elif id_dts is None and err[0] == 500:
            raise falcon.HTTPInternalServerError(description=err[1])
        else:
            # Dataset created, evrything is done
            resp.status = falcon.HTTP_201
            resp.body = json.dumps({"dataset": {"id": id_dts}})
            resp.location = "/datasets/" + str(id_dts)
项目:falsy    作者:pingf    | 项目源码 | 文件源码
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)
项目:iris-relay    作者:linkedin    | 项目源码 | 文件源码
def on_post(self, req, resp):
        """
        Accept slack's message from interactive buttons
        """
        try:
            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('callback_id not found in the json payload.')
                raise falcon.HTTPBadRequest('Bad Request', 'Callback id not found')
            except ValueError as 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 is not 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')
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def do_get(self, req, resp, hostname, asset_type):
        """Render ``unit`` type boot action assets for hostname.

        Get the boot action context for ``hostname`` from the database
        and render all ``unit`` type assets for the host. Validate host
        is providing the correct idenity key in the ``X-Bootaction-Key``
        header.

        :param req: falcon request object
        :param resp: falcon response object
        :param hostname: URL path parameter indicating the calling host
        :param asset_type: Asset type to include in the response - ``unit``, ``file``, ``pkg_list``, ``all``
        """
        try:
            ba_ctx = self.state_manager.get_boot_action_context(hostname)
        except Exception as ex:
            self.logger.error(
                "Error locating boot action for %s" % hostname, exc_info=ex)
            raise falcon.HTTPNotFound()

        if ba_ctx is None:
            raise falcon.HTTPNotFound(
                description="Error locating boot action for %s" % hostname)

        BootactionUtils.check_auth(ba_ctx, req)

        asset_type_filter = None if asset_type == 'all' else asset_type

        try:
            task = self.state_manager.get_task(ba_ctx['task_id'])
            design_status, site_design = self.orchestrator.get_effective_site(
                task.design_ref)

            assets = list()
            ba_status_list = self.state_manager.get_boot_actions_for_node(
                hostname)

            for ba in site_design.bootactions:
                if hostname in ba.target_nodes:
                    ba_status = ba_status_list.get(ba.name, None)
                    action_id = ba_status.get('action_id')
                    assets.extend(
                        ba.render_assets(
                            hostname,
                            site_design,
                            action_id,
                            type_filter=asset_type_filter))

            tarball = BootactionUtils.tarbuilder(asset_list=assets)
            resp.set_header('Content-Type', 'application/gzip')
            resp.set_header('Content-Disposition',
                            "attachment; filename=\"%s-%s.tar.gz\"" %
                            (hostname, asset_type))
            resp.data = tarball
            resp.status = falcon.HTTP_200
            return
        except Exception as ex:
            self.logger.debug("Exception in boot action API.", exc_info=ex)
            raise falcon.HTTPInternalServerError(str(ex))
项目:falsy    作者:pingf    | 项目源码 | 文件源码
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()