当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.HTTPException方法代码示例

本文整理汇总了Python中werkzeug.exceptions.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.HTTPException方法的具体用法?Python exceptions.HTTPException怎么用?Python exceptions.HTTPException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.exceptions的用法示例。


在下文中一共展示了exceptions.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: new_handle_http_exception

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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) 
开发者ID:pgjones,项目名称:quart,代码行数:20,代码来源:app.py

示例2: test_get_identity_403

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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)) 
开发者ID:spoqa,项目名称:geofront,代码行数:20,代码来源:server_test.py

示例3: broad_exception_handler

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:JoMingyu,项目名称:Flask-Large-Application-Example,代码行数:23,代码来源:error.py

示例4: send

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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')) 
开发者ID:miguelgrinberg,项目名称:api-pycon2014,代码行数:22,代码来源:test_client.py

示例5: _interface_by_mac

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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)) 
开发者ID:openstack,项目名称:octavia,代码行数:25,代码来源:plug.py

示例6: test__interface_by_mac_not_found

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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') 
开发者ID:openstack,项目名称:octavia,代码行数:18,代码来源:test_plug.py

示例7: can_handle_request

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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) 
开发者ID:italia,项目名称:daf-recipes,代码行数:21,代码来源:flask_app.py

示例8: handle_exception

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:marcopaz,项目名称:is-service-up,代码行数:18,代码来源:exceptions.py

示例9: test_SupervisorRolePermission_authenticated_user_with_password_with_check_supervisor

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:21,代码来源:test_permissions.py

示例10: test_SupervisorRolePermission_authenticated_user_with_password_without_check_supervisor

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:22,代码来源:test_permissions.py

示例11: test_OwnerRolePermission_authenticated_user_with_password_with_check_owner

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:21,代码来源:test_permissions.py

示例12: test_OwnerRolePermission_authenticated_user_with_password_without_check_owner

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:22,代码来源:test_permissions.py

示例13: handle_base_except

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:22,代码来源:decorators.py

示例14: normalize

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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) 
开发者ID:hashedin,项目名称:squealy,代码行数:18,代码来源:parameters.py

示例15: get_error_details_and_status

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import HTTPException [as 别名]
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 
开发者ID:uc-cdis,项目名称:fence,代码行数:27,代码来源:error_handler.py


注:本文中的werkzeug.exceptions.HTTPException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。