本文整理汇总了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)
示例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))
示例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
示例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'))
示例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))
示例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')
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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)
示例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