Python werkzeug.exceptions.HTTPException() Examples

The following are 30 code examples of werkzeug.exceptions.HTTPException(). 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 werkzeug.exceptions , or try the search function .
Example #1
Source File: error.py    From Flask-Large-Application-Example with MIT License 7 votes vote down vote up
def broad_exception_handler(e: Exception):
    # TODO 에러를 세분화해서 잡는 것을 추천합니다.

    if isinstance(e, HTTPException):
        message = e.description
        code = e.code

    elif isinstance(e, ValidationError):
        message = json.loads(e.json())
        code = HTTPStatus.BAD_REQUEST

    else:
        message = ""
        code = HTTPStatus.INTERNAL_SERVER_ERROR

        if current_app.debug:
            import traceback

            traceback.print_exc()

    return jsonify({"error": message}), code 
Example #2
Source File: tfserve.py    From tfserve with MIT License 6 votes vote down vote up
def _init_app(self, middleware=None):
        """Initialize a WSGI application for handling POST to '/'.

        `middleware` may be provided as WSGI middleware.

        """
        routes = routing.Map([
            routing.Rule('/', endpoint=self._handle_inference),
            routing.Rule('/ping', endpoint=self._handle_ping),
            routing.Rule('/shutdown', endpoint=self._handle_shutdown),
        ])
        def app(env, start_resp):
            """WSGI application to handle server requests.

            """
            urls = routes.bind_to_environ(env)
            try:
                handler, _kw = urls.match()
                req = Request(env)
                if middleware:
                    return middleware(handler, req)(env, start_resp)
                return handler(req)(env, start_resp)
            except HTTPException as e:
                return e(env, start_resp)
        return app 
Example #3
Source File: test_client.py    From api-pycon2014 with MIT License 6 votes vote down vote up
def send(self, url, method='GET', data=None, headers={}):
        headers = headers.copy()
        headers['Authorization'] = self.auth
        headers['Content-Type'] = 'application/json'
        headers['Accept'] = 'application/json'
        if data:
            data = json.dumps(data)

        with self.app.test_request_context(url, method=method, data=data,
                                           headers=headers):
            try:
                rv = self.app.preprocess_request()
                if rv is None:
                    rv = self.app.dispatch_request()
                rv = self.app.make_response(rv)
                rv = self.app.process_response(rv)
            except HTTPException as e:
                rv = self.app.handle_user_exception(e)

        return rv, json.loads(rv.data.decode('utf-8')) 
Example #4
Source File: server_test.py    From geofront with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_identity_403(fx_app, fx_token_store, fx_token_id):
    expires_at = (datetime.datetime.now(datetime.timezone.utc) +
                  datetime.timedelta(hours=1))
    fx_token_store.set(
        fx_token_id,
        Token(Identity(DummyTeam, 1, False), expires_at)
    )
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 403
            data = json.loads(response.get_data())
            assert data['error'] == 'not-authorized'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example #5
Source File: plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _interface_by_mac(self, mac):
        try:
            with pyroute2.IPRoute() as ipr:
                idx = ipr.link_lookup(address=mac)[0]
                addr = ipr.get_links(idx)[0]
                for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404)) 
Example #6
Source File: test_plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test__interface_by_mac_not_found(self, mock_ipr):
        mock_ipr_instance = mock.MagicMock()
        mock_ipr_instance.link_lookup.return_value = []
        mock_ipr().__enter__.return_value = mock_ipr_instance

        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        isfile_mock = mock.Mock()
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock), mock.patch.object(
                os.path, 'isfile', isfile_mock):
            self.assertRaises(wz_exceptions.HTTPException,
                              self.test_plug._interface_by_mac,
                              FAKE_MAC_ADDRESS.upper())
        open_mock.assert_called_once_with('/sys/bus/pci/rescan', os.O_WRONLY)
        fd_mock().write.assert_called_once_with('1') 
Example #7
Source File: flask_app.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def can_handle_request(self, environ):
        '''
        Decides whether it can handle a request with the Flask app by
        matching the request environ against the route mapper

        Returns (True, 'flask_app') if this is the case.
        '''

        # TODO: identify matching urls as core or extension. This will depend
        # on how we setup routing in Flask

        urls = self.url_map.bind_to_environ(environ)
        try:
            endpoint, args = urls.match()
            log.debug('Flask route match, endpoint: {0}, args: {1}'.format(
                endpoint, args))
            return (True, self.app_name)
        except HTTPException:
            return (False, self.app_name) 
Example #8
Source File: exceptions.py    From is-service-up with Apache License 2.0 6 votes vote down vote up
def handle_exception(error):
    code = 500
    message = None
    if hasattr(error, 'status_code') :
        code = error.status_code
    if hasattr(error, 'message') :
        message = str(error.message)
    if isinstance(error, HTTPException):
        code = error.code
        message = str(error)

    extra = error.extra if hasattr(error, 'extra') else None

    response = jsonify(format_exception(message, code=code, extra=extra))
    response.status_code = code
    return response 
Example #9
Source File: test_permissions.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def test_SupervisorRolePermission_authenticated_user_with_password_with_check_supervisor(
        authenticated_user_instance
):
    authenticated_user_instance.password = "correct_password"
    obj = Mock()
    obj.check_supervisor = lambda user: user == authenticated_user_instance
    with permissions.SupervisorRolePermission(
        obj=obj,
        password_required=True,
        password="correct_password"
    ):
        pass
    with pytest.raises(HTTPException):
        with permissions.SupervisorRolePermission(
            obj=obj,
            password_required=True,
            password="wrong_password"
        ):
            pass 
Example #10
Source File: test_permissions.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def test_SupervisorRolePermission_authenticated_user_with_password_without_check_supervisor(
        authenticated_user_instance
):
    authenticated_user_instance.password = "correct_password"
    obj = Mock()
    del obj.check_supervisor
    with pytest.raises(HTTPException):
        with permissions.SupervisorRolePermission(
            obj=obj,
            password_required=True,
            password="correct_password"
        ):
            pass
    with pytest.raises(HTTPException):
        with permissions.SupervisorRolePermission(
            obj=obj,
            password_required=True,
            password="wrong_password"
        ):
            pass 
Example #11
Source File: test_permissions.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def test_OwnerRolePermission_authenticated_user_with_password_with_check_owner(
        authenticated_user_instance
):
    authenticated_user_instance.password = "correct_password"
    obj = Mock()
    obj.check_owner = lambda user: user == authenticated_user_instance
    with permissions.OwnerRolePermission(
        obj=obj,
        password_required=True,
        password="correct_password"
    ):
        pass
    with pytest.raises(HTTPException):
        with permissions.OwnerRolePermission(
            obj=obj,
            password_required=True,
            password="wrong_password"
        ):
            pass 
Example #12
Source File: decorators.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def handle_base_except(f):
    """Wrapper which handles base exceptions."""
    # noqa
    @wraps(f)
    def decorated_function(*args, **kwargs):
        """Represents decorated function."""
        try:
            return f(*args, **kwargs)
        except HTTPException as e:  # handle general werkzeug exception
            return error_response(e.code, e.description)

        except (Exception, BaseException, OSError, IOError) as e:
            internal_error = 'internal error'
            if hasattr(e, 'stderr'):
                internal_error += ': {0}'.format(
                    ' '.join(e.stderr.strip().split('\n'))
                )
            return error_response(INTERNAL_FAILURE_ERROR_CODE, internal_error)

    return decorated_function 
Example #13
Source File: app.py    From quart with MIT License 6 votes vote down vote up
def new_handle_http_exception(
    self: Quart, error: Union[WerkzeugHTTPException, QuartHTTPException]
) -> Response:
    if isinstance(error, WerkzeugHTTPException):
        handler = self._find_exception_handler(error)
        if handler is None:
            werkzeug_response = error.get_response()
            return await self.make_response(
                (
                    werkzeug_response.get_data(),
                    werkzeug_response.status_code,
                    werkzeug_response.headers,
                )
            )
        else:
            return await handler(error)
    else:
        return await old_handle_http_exception(self, error) 
Example #14
Source File: routing.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test(self, path_info=None, method=None):
        """Test if a rule would match.  Works like `match` but returns `True`
        if the URL matches, or `False` if it does not exist.

        :param path_info: the path info to use for matching.  Overrides the
                          path info specified on binding.
        :param method: the HTTP method used for matching.  Overrides the
                       method specified on binding.
        """
        try:
            self.match(path_info, method)
        except RequestRedirect:
            pass
        except HTTPException:
            return False
        return True 
Example #15
Source File: engine.py    From appkernel with Apache License 2.0 6 votes vote down vote up
def generic_error_handler(self, ex: Exception = None, upstream_service: str = None):
        """
        Takes a generic exception and returns a json error message which will be returned to the client
        :param ex: the exception which is reported by this method
        :param upstream_service: the servicr name which generated this error
        :return:
        """
        code = (ex.code if isinstance(ex, HTTPException) else 500)
        if ex and code != 404:
            msg = '{}/{}'.format(ex.__class__.__name__, ex.description if isinstance(ex, HTTPException) else str(ex))
            self.logger.exception('generic error handler: {}/{}'.format(ex.__class__.__name__, str(ex)))
        elif ex and code == 404:
            msg = '{} ({} {}): {}'.format(ex.__class__.__name__, request.method, request.url,
                                          ex.description if isinstance(ex, HTTPException) else str(ex))
            self.logger.exception('generic error handler: {}/{}'.format(ex.__class__.__name__, str(ex)))
        else:
            msg = 'Generic server error.'
            self.logger.warning('generic error handler: {}/{}'.format(ex.__class__.__name__, str(ex)))
        return create_custom_error(code, msg, upstream_service=upstream_service) 
Example #16
Source File: error.py    From spendb with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle_error(exc):
    status = 500
    title = exc.__class__.__name__
    message = unicode(exc)
    headers = {}
    if isinstance(exc, HTTPException):
        message = exc.get_description(request.environ)
        message = message.replace('<p>', '').replace('</p>', '')
        status = exc.code
        title = exc.name
        headers = exc.get_headers(request.environ)
    data = {
        'status': status,
        'title': title,
        'message': message
    }
    return jsonify(data, status=status, headers=headers) 
Example #17
Source File: util.py    From OpenDCRE with GNU General Public License v2.0 6 votes vote down vote up
def _make_json_error(ex):
    """ Create a JSON response for an exception raised in the endpoint.

    Args:
        ex (Exception): The exception raised.

    Returns:
        Response: a Flask response with the proper json error message and
            status code.
    """
    if isinstance(ex, HTTPException):
        message = ex.description
        http_code = ex.code
    else:
        message = ex.message
        http_code = 500

    response = jsonify(
        message=str(message),
        http_code=http_code
    )
    response.status_code = http_code

    return response 
Example #18
Source File: excep_register.py    From Flask_BestPractices with MIT License 6 votes vote down vote up
def errors(e):
    print('异常:', e)
    print('异常类型:', type(e))

    if isinstance(e, CustomException):
        print('-----CustomException-----')
        tb('-----CustomException-----')
        return api_result(code=e.code, message='CustomException:【{}】'.format(str(e.msg)),
                          data=request.method + ' ' + request.path)

    if isinstance(e, HTTPException) and (300 <= e.code < 600):
        print('-----HTTPException-----')
        tb('-----HTTPException-----')
        return api_result(code=e.code, message='HTTPException:【{}】'.format(str(e)),
                          data=request.method + ' ' + request.path)

    else:
        print('-----Exception-----')
        tb('-----Exception-----')
        return api_result(code=500, message='Exception:【{}】'.format(str(e)), data=request.method + ' ' + request.path) 
Example #19
Source File: error_handler.py    From fence with Apache License 2.0 6 votes vote down vote up
def get_error_details_and_status(error):
    message = error.message if hasattr(error, "message") else str(error)
    if isinstance(error, APIError):
        if hasattr(error, "json") and error.json:
            error.json["message"] = message
            error_response = error.json, error.code
        else:
            error_response = {"message": message}, error.code
    elif isinstance(error, OAuth2Error):
        error_response = {"message": error.description}, error.status_code
    elif isinstance(error, HTTPException):
        error_response = (
            {"message": getattr(error, "description")},
            error.get_response().status_code,
        )
    else:
        logger.exception("Catch exception")
        error_code = 500
        if hasattr(error, "code"):
            error_code = error.code
        elif hasattr(error, "status_code"):
            error_code = error.status_code
        error_response = {"message": message}, error_code

    return error_response 
Example #20
Source File: parameters.py    From squealy with MIT License 6 votes vote down vote up
def normalize(self, value):
        if not value and self.default_value:
            value = self.default_value
        if not value:
            if self.mandatory:
                raise RequiredParameterMissingException(name)
            else:
                return None
        
        if not self.is_valid(value):
            raise HTTPException(code=400)

        if isinstance(value, str):
            return value
        else:
            return str(value) 
Example #21
Source File: test_permissions.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def test_OwnerRolePermission_authenticated_user_with_password_without_check_owner(
        authenticated_user_instance
):
    authenticated_user_instance.password = "correct_password"
    obj = Mock()
    del obj.check_owner
    with pytest.raises(HTTPException):
        with permissions.OwnerRolePermission(
            obj=obj,
            password_required=True,
            password="correct_password"
        ):
            pass
    with pytest.raises(HTTPException):
        with permissions.OwnerRolePermission(
            obj=obj,
            password_required=True,
            password="wrong_password"
        ):
            pass 
Example #22
Source File: server_test.py    From geofront with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_identity_412(fx_app, fx_token_store, fx_token_id):
    fx_token_store.set(fx_token_id, 'nonce')
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 412
            data = json.loads(response.get_data())
            assert data['error'] == 'unfinished-authentication'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example #23
Source File: __init__.py    From notifications-api with MIT License 5 votes vote down vote up
def init_app(app):

    @app.before_request
    def record_request_details():
        CONCURRENT_REQUESTS.inc()

        g.start = monotonic()
        g.endpoint = request.endpoint

    @app.after_request
    def after_request(response):
        CONCURRENT_REQUESTS.dec()

        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    @app.errorhandler(Exception)
    def exception(error):
        app.logger.exception(error)
        # error.code is set for our exception types.
        msg = getattr(error, 'message', str(error))
        code = getattr(error, 'code', 500)
        return jsonify(result='error', message=msg), code

    @app.errorhandler(WerkzeugHTTPException)
    def werkzeug_exception(e):
        return make_response(
            jsonify(result='error', message=e.description),
            e.code,
            e.get_headers()
        )

    @app.errorhandler(404)
    def page_not_found(e):
        msg = e.description or "Not found"
        return jsonify(result='error', message=msg), 404 
Example #24
Source File: ctx.py    From Flask-P2P with MIT License 5 votes vote down vote up
def match_request(self):
        """Can be overridden by a subclass to hook into the matching
        of the request.
        """
        try:
            url_rule, self.request.view_args = \
                self.url_adapter.match(return_rule=True)
            self.request.url_rule = url_rule
        except HTTPException as e:
            self.request.routing_exception = e 
Example #25
Source File: server_test.py    From geofront with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_identity_404(fx_app, fx_token_id):
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 404
            data = json.loads(response.get_data())
            assert data['error'] == 'token-not-found'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example #26
Source File: backends.py    From stackhut with Apache License 2.0 5 votes vote down vote up
def local_server(self, request):
        """
        Local webserver running on separate thread for dev usage
        Sends msgs to LocalBackend over a pair of shared queues
        """
        adapter = self.url_map.bind_to_environ(request.environ)
        try:
            endpoint, values = adapter.match()
            return getattr(self, 'on_' + endpoint)(request, **values)
        except HTTPException as e:
            return e 
Example #27
Source File: ctx.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
def match_request(self):
        """Can be overridden by a subclass to hook into the matching
        of the request.
        """
        try:
            url_rule, self.request.view_args = \
                self.url_adapter.match(return_rule=True)
            self.request.url_rule = url_rule
        except HTTPException as e:
            self.request.routing_exception = e 
Example #28
Source File: ctx.py    From scylla with Apache License 2.0 5 votes vote down vote up
def match_request(self):
        """Can be overridden by a subclass to hook into the matching
        of the request.
        """
        try:
            url_rule, self.request.view_args = \
                self.url_adapter.match(return_rule=True)
            self.request.url_rule = url_rule
        except HTTPException as e:
            self.request.routing_exception = e 
Example #29
Source File: ctx.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def match_request(self):
        """Can be overridden by a subclass to hook into the matching
        of the request.
        """
        try:
            url_rule, self.request.view_args = \
                self.url_adapter.match(return_rule=True)
            self.request.url_rule = url_rule
        except HTTPException as e:
            self.request.routing_exception = e 
Example #30
Source File: api.py    From flask-resty with MIT License 5 votes vote down vote up
def init_app(self, app):
        """Initialize an application for use with Flask-RESTy.

        :param app: The Flask application object.
        :type app: :py:class:`flask.Flask`
        """
        app.extensions["resty"] = FlaskRestyState(self)

        app.register_error_handler(ApiError, handle_api_error)
        app.register_error_handler(HTTPException, handle_http_exception)