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

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

项目:og-miner    作者:opendns    | 项目源码 | 文件源码
def on_post(self, request, response):
        query = dict()
        try:
            raw_json = request.stream.read()
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        try:
            data = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')

        if "id" not in data:
            raise falcon.HTTPConflict('Task creation', "ID is not specified.")
        if "type" not in data:
            raise falcon.HTTPConflict('Task creation', "Type is not specified.")

        transaction = self.client.push_task({ "task" : "vertex", "data" : data })

        response.body = json.dumps({ "transaction" : transaction })
        response.status = falcon.HTTP_202
项目:falcon-api    作者:Opentopic    | 项目源码 | 文件源码
def handle(ex, req, resp, params):
        """
        :param ex: the exception
        :type ex: Exception

        :param req: Falcon request
        :type req: falcon.request.Request

        :param resp: Falcon response
        :type resp: falcon.response.Response

        :param params: parameters dict
        :type params: dict

        :raises falcon.HTTPError
        """
        logger = logging.getLogger()
        if not isinstance(ex, falcon.HTTPError):
            logger.error('Non-HTTP exception occurred ({}): {}'.format(type(ex), ex), exc_info=ex)
            ex = falcon.HTTPError(falcon.HTTP_500, str(type(ex)), str(ex))
        else:
            logger.warning('HTTP exception occurred ({}): {}'.format(type(ex), ex), exc_info=ex)
        raise ex
项目:falcon-api    作者:Opentopic    | 项目源码 | 文件源码
def handle(self, ex, req, resp, params):
        """
        :param ex: the exception
        :type ex: Exception

        :param req: Falcon request
        :type req: falcon.request.Request

        :param resp: Falcon response
        :type resp: falcon.response.Response

        :param params: parameters dict
        :type params: dict
        """
        logger = logging.getLogger()
        if not isinstance(ex, falcon.HTTPError):
            logger.error('Non-HTTP exception occurred ({}): {}'.format(type(ex), ex), exc_info=ex)
            ex = falcon.HTTPError(falcon.HTTP_500, str(type(ex)), str(ex))
        template = self.translator.get_error_template(ex.status)
        resp.status = ex.status
        if ex.headers:
            resp.set_headers(ex.headers)
        resp.body = template.render(**HtmlTranslator.get_template_vars(ex.to_dict(), req))
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def default_exception_handler(ex, req, resp, params):
    """Catch-all execption handler for standardized output.

    If this is a standard falcon HTTPError, rethrow it for handling by
    ``default_exception_serializer`` below.
    """
    if isinstance(ex, falcon.HTTPError):
        # Allow the falcon http errors to bubble up and get handled.
        raise ex
    else:
        # Take care of the uncaught stuff.
        exc_string = traceback.format_exc()
        LOG.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % six.text_type(ex)
        )
项目:armada    作者:att-comdev    | 项目源码 | 文件源码
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all execption handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        logging.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True
        )
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def process_request(self, req, resp):
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Nothing to do
            return

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                                        'A valid JSON document is required.')

        try:
            req.context['doc'] = json.loads(body.decode('utf-8'))

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')
项目:promenade    作者:att-comdev    | 项目源码 | 文件源码
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all exception handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        LOG.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True)
项目:EVA    作者:metno    | 项目源码 | 文件源码
def process_request(self, req, resp):
        req.context['body'] = ''
        if req.content_length in (None, 0):
            return

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.')

        try:
            req.context['body'] = body.decode('utf-8')
            req.context['doc'] = json.loads(req.context['body'])

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(
                falcon.HTTP_753,
                'Malformed JSON', 'Could not decode the request body. The JSON was incorrect or not encoded as UTF-8.',
            )
项目:plex-watched-sync    作者:fiLLLip    | 项目源码 | 文件源码
def on_put(self, req, resp, account_id):
        """Handles PUT requests"""
        try:
            raw_json = req.stream.read()
        except Exception as ex:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Error',
                                   ex.message)

        try:
            result_json = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        items = result_json['watched']
        result = Actions.add_watched_to_account(account_id, items)
        resp.status = falcon.HTTP_202
        jsonresp = {'account_id': account_id, 'tried_to_add': items, 'added': result}
        resp.body = json.dumps(jsonresp)
项目: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))
项目:falcon-api    作者:Opentopic    | 项目源码 | 文件源码
def process_request(self, req, resp):
        """
        Converts request input data from JSON to a dict.
        :param req: Falcon request
        :type req: falcon.request.Request

        :param resp: Falcon response
        :type resp: falcon.response.Response
        """
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Nothing to do
            return

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                                        'A valid JSON document is required.')

        try:
            req.context['doc'] = json.loads(body.decode('utf-8'))

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def default_exception_serializer(req, resp, exception):
    """Serializes instances of :class:`falcon.HTTPError` into YAML format and
    formats the error body so it adheres to the UCP error formatting standard.
    """
    format_error_resp(
        req,
        resp,
        status_code=exception.status,
        # TODO(fmontei): Provide an overall error message instead.
        message=exception.description,
        reason=exception.title,
        error_type=exception.__class__.__name__,
        error_list=[{'message': exception.description, 'error': True}]
    )
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def test_falcon_exception_formatting(self):
        """Verify formatting for an exception class that inherits from
        :class:`falcon.HTTPError`.
        """
        expected_msg = (
            'deckhand:create_cleartext_documents is disallowed by policy')

        with mock.patch.object(
                policy, '_do_enforce_rbac',
                spec_set=policy._do_enforce_rbac) as m_enforce_rbac:
            m_enforce_rbac.side_effect = falcon.HTTPForbidden(
                description=expected_msg)
            resp = self.app.simulate_put(
                '/api/v1.0/buckets/test/documents',
                headers={'Content-Type': 'application/x-yaml'}, body=None)

        expected = {
            'status': 'Failure',
            'kind': 'status',
            'code': '403 Forbidden',
            'apiVersion': 'v1.0',
            'reason': '403 Forbidden',
            'retry': False,
            'details': {
                'errorType': 'HTTPForbidden',
                'errorCount': 1,
                'messageList': [
                    {
                        'message': expected_msg,
                        'error': True
                    }
                ]
            },
            'message': expected_msg,
            'metadata': {}
        }
        body = yaml.safe_load(resp.text)

        self.assertEqual(403, resp.status_code)
        self.assertEqual(expected, body)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def handle(ex, req, resp, params):
        raise falcon.HTTPError(
            falcon.HTTP_792,
            u'Internet crashed!',
            u'Catastrophic weather event',
            href=u'http://example.com/api/inconvenient-truth',
            href_text=u'Drill, baby drill!')
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def validate_output(req, resp):
    raise falcon.HTTPError(falcon.HTTP_723, 'Tricky')
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def handle(ex, req, resp, params):
        description = ('Sorry, couldn\'t write your thing to the '
                       'database. It worked on my box.')

        raise falcon.HTTPError(falcon.HTTP_725,
                               'Database Error',
                               description)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_multiple_reponse_mw_throw_exception(self):
        """Test that error in inner middleware leaves"""
        global context

        context['req_succeeded'] = []

        class RaiseStatusMiddleware(object):
            def process_response(self, req, resp, resource):
                raise falcon.HTTPStatus(falcon.HTTP_201)

        class RaiseErrorMiddleware(object):
            def process_response(self, req, resp, resource):
                raise falcon.HTTPError(falcon.HTTP_748)

        class ProcessResponseMiddleware(object):
            def process_response(self, req, resp, resource, req_succeeded):
                context['executed_methods'].append('process_response')
                context['req_succeeded'].append(req_succeeded)

        app = falcon.API(middleware=[ProcessResponseMiddleware(),
                                     RaiseErrorMiddleware(),
                                     ProcessResponseMiddleware(),
                                     RaiseStatusMiddleware(),
                                     ProcessResponseMiddleware()])

        app.add_route(TEST_ROUTE, MiddlewareClassResource())
        client = testing.TestClient(app)

        response = client.simulate_request(path=TEST_ROUTE)

        assert response.status == falcon.HTTP_748

        expected_methods = ['process_response'] * 3
        assert context['executed_methods'] == expected_methods
        assert context['req_succeeded'] == [True, False, False]
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def on_get(self, req, resp):
        status = req.get_header('X-Error-Status')
        title = req.get_header('X-Error-Title')
        description = req.get_header('X-Error-Description')
        code = 10042

        raise falcon.HTTPError(status, title, description, code=code)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def on_put(self, req, resp):
        raise falcon.HTTPError(
            falcon.HTTP_792,
            'Internet crashed',
            'Catastrophic weather event due to climate change.',
            href='http://example.com/api/climate',
            href_text='Drill baby drill!',
            code=8733224)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def on_patch(self, req, resp):
        raise falcon.HTTPError(falcon.HTTP_400)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def on_get(self, req, resp):
        self.called = True
        raise falcon.HTTPError(
            falcon.HTTP_792,
            u'Internet \xe7rashed!',
            u'\xc7atastrophic weather event',
            href=u'http://example.com/api/\xe7limate',
            href_text=u'Drill b\xe1by drill!')
项目:og-miner    作者:opendns    | 项目源码 | 文件源码
def on_post(self, request, response, vertex_id):
        query = dict()
        try:
            raw_json = request.stream.read()
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        try:
            data = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')

        data["id"] = vertex_id
        try:
            query = list(graph.query_vertices({ "id" : vertex_id }))
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        if len(query) > 0:
            raise falcon.HTTPConflict('Vertex Creation', "Vertex already exists.")

        try:
            result = graph.update_vertex(**data)
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        response.status = falcon.HTTP_200
        response.body = json.dumps({ "created" : result }, encoding='utf-8')
项目:orbital-cotwo-web    作者:chronos-pramantha    | 项目源码 | 文件源码
def process_request(self, req, resp):
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Request body is void, nothing to do
            raise falcon.HTTPBadRequest(
                'Empty request body',
                'A valid GeoJSON document is required.'
            )

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                                        'A valid JSON document is required.')

        try:
            req.context['geojson'] = body.decode('utf-8')
            # #todo: use geojson.is_valid
            json.loads(req.context['geojson'])
        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')
项目:falcon-sqlalchemy    作者:vixcess    | 项目源码 | 文件源码
def parse_json(req, resp, resource, params):
    # if not json data, do nothing
    if req.content_type is None or 'application/json' not in req.content_type:
        return

    # req.stream corresponds to the WSGI wsgi.input environ variable,
    # and allows you to read bytes from the request body.
    #
    # See also: PEP 3333
    if req.content_length in (None, 0):
        # Nothing to do
        return

    body = req.stream.read()
    if not body:
        raise falcon.HTTPBadRequest('Empty request body',
                                    'A valid JSON document is required.')

    try:
        req.context['doc'] = json.loads(body.decode('utf-8'))

    except (ValueError, UnicodeDecodeError):
        raise falcon.HTTPError(falcon.HTTP_753,
                               'Malformed JSON',
                               'Could not decode the request body. The '
                               'JSON was incorrect or not encoded as '
                               'UTF-8.')
项目:falcon-api-redis    作者:kentsay    | 项目源码 | 文件源码
def on_post(self, req, resp, doc_index):
        try:
            raw_json = req.stream.read()
        except Exception as ex:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Error',
                ex.message)
        try:
            result_json = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The JSON was incorrect.')

        """
        Enqueueing write request as jobs into document_write queue
        and processing them in the background with workers.
        """
        q = Queue('document_write', connection=self.db.connection())
        job = q.enqueue_call(
            func=postDocument, args=(result_json, doc_index), result_ttl=5000
        )
        LOG.info('POST request ' + str(job.get_id()))

        resp.status = falcon.HTTP_202
        resp.body = json.dumps(result_json, encoding='utf-8')


    # This function handles DELETE reuqests
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def register_error_handlers(self):
        """Register error handlers"""
        api = self.app_context.api
        api.add_error_handler(ValueError, error.value_error_handler)
        api.add_error_handler(HTTPError, error.http_error_handler)

        self.trigger_manager.error_handler = error.DefaultErrorHandler()
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def register_error_handlers(self):
        """Register error handlers"""
        api = self.app_context.api
        api.add_error_handler(ValueError, error.value_error_handler)
        api.add_error_handler(HTTPError, error.http_error_handler)

        self.trigger_manager.error_handler = error.DefaultErrorHandler()
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def default_error_handler(ex, req, resp, params):
    """Error handler for all exceptions"""
    error_handlers = {
        ValueError: value_error_handler,
        HTTPError: http_error_handler,
        BaseException: base_error_handler
    }
    if resp is not None:
        for ex_type in error_handlers:
            if isinstance(ex, ex_type):
                handler = error_handlers.get(ex_type)
                handler(ex, req, resp, params)
                break

    distress_call(ex)
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def http_error_handler(ex, req, resp, params):
    """Error handler for HTTPError"""
    resp.body = encode.encode({
        'status': 1,
        'msg': 'HTTP error: ' + ex.status
    })
项目:plex-watched-sync    作者:fiLLLip    | 项目源码 | 文件源码
def on_put(self, req, resp, server_id):
        """Handles PUT requests"""
        resp.status = falcon.HTTP_404 # Disabled!
        return

        try:
            raw_json = req.stream.read()
        except Exception as ex:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Error',
                                   ex.message)

        try:
            result_json = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        accounts = Actions.get_accounts(server_id)
        if accounts is None:
            resp.status = falcon.HTTP_404
            return

        accounts = result_json['accounts']
        for account_id in accounts:
            Actions.add_account(server_id, account_id)
            account.Actions.add_server(account_id, server_id)

        resp.status = falcon.HTTP_200  # This is the default status
        jsonresp = {'server_id': server_id, 'accounts': Actions.get_accounts(server_id)}
        resp.body = json.dumps(jsonresp)
项目:falcon-boilerplate    作者:admiralobvious    | 项目源码 | 文件源码
def __init__(self, status, description, **kwargs):
        http_status = "HTTP_{}".format(status)
        if hasattr(status_codes, http_status):
            title = getattr(status_codes, http_status)
        else:
            raise ValueError("Status code '{}' does not exist!".format(http_status))
        super(HTTPError, self).__init__(title, title, str(description), **kwargs)
项目:falcon-boilerplate    作者:admiralobvious    | 项目源码 | 文件源码
def error_handler(ex, req, resp, params):
    if not isinstance(ex, falcon.HTTPError):
        logger.exception("Unhandled error while processing request: {}".format(ex))
        raise HTTPError(500, str(ex))
    else:
        raise ex
项目:Python-Journey-from-Novice-to-Expert    作者:PacktPublishing    | 项目源码 | 文件源码
def process_request(self, req, resp):
        self.set_access_control_allow_origin(resp)

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                'A valid JSON document is required.')
        try:
            req.context['_body'] = json.loads(
                body.decode('utf-8'))
        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(
                falcon.HTTP_753, 'Malformed JSON',
                'JSON incorrect or not utf-8 encoded.')
项目:falcon-swagger    作者:dutradda    | 项目源码 | 文件源码
def __init__(self, models, sqlalchemy_bind=None, redis_bind=None,
                 middleware=None, router=None, swagger_template=None,
                 title=None, version='1.0.0', authorizer=None):
        if sqlalchemy_bind is not None or redis_bind is not None:
            sess_mid = SessionMiddleware(sqlalchemy_bind, redis_bind)

            if middleware is None:
                middleware = sess_mid
            else:
                middleware.append(sess_mid)

        if router is None:
            router = ModelRouter()

        API.__init__(self, router=router, middleware=middleware)
        self._build_logger()

        type(self).__schema_dir__ = get_module_path(type(self))

        if bool(title is None) == bool(swagger_template is None):
            raise SwaggerAPIError("One of 'title' or 'swagger_template' "
                                  "arguments must be setted.")

        if version != '1.0.0' and swagger_template is not None:
            raise SwaggerAPIError("'version' argument can't be setted when "
                                  "'swagger_template' was setted.")

        self._set_swagger_template(swagger_template, title, version)

        self._logger = logging.getLogger(type(self).__module__ + '.' + type(self).__name__)
        self.models = dict()
        self.add_route = None
        del self.add_route

        for model in models:
            self.associate_model(model)

        self._set_swagger_json_route(authorizer)

        self.add_error_handler(Exception, self._handle_generic_error)
        self.add_error_handler(HTTPError, self._handle_http_error)
        self.add_error_handler(IntegrityError, self._handle_integrity_error)
        self.add_error_handler(
            ValidationError, self._handle_json_validation_error)
        self.add_error_handler(JSONError)
        self.add_error_handler(ModelBaseError)
        self.add_error_handler(UnauthorizedError)