本文整理匯總了Python中http.HTTPStatus.FORBIDDEN屬性的典型用法代碼示例。如果您正苦於以下問題:Python HTTPStatus.FORBIDDEN屬性的具體用法?Python HTTPStatus.FORBIDDEN怎麽用?Python HTTPStatus.FORBIDDEN使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類http.HTTPStatus
的用法示例。
在下文中一共展示了HTTPStatus.FORBIDDEN屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: anonymous_user_required
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
"""
Decorator requiring that there is no user currently logged in.
Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
"""
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated:
if request.is_json:
abort(HTTPStatus.FORBIDDEN)
else:
if msg:
flash(msg, category)
return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
override=redirect_url)
return fn(*args, **kwargs)
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapper(decorator_args[0])
return wrapper
示例2: anonymous_user_required
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def anonymous_user_required(*args, **kwargs):
"""Decorator requiring no user be logged in
Aborts with HTTP 403: Forbidden if there is an authenticated user
"""
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated:
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated
if was_decorated_without_parenthesis(args):
return wrapper(args[0])
return wrapper
示例3: test__enter_rescue_mode_operation_not_allowed
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def test__enter_rescue_mode_operation_not_allowed(self):
machine = make_machines_origin().Machine(
{
"system_id": make_name_without_spaces("system-id"),
"hostname": make_name_without_spaces("hostname"),
}
)
# Mock the call to content.decode in the CallError constructor
content = Mock()
content.decode = Mock(return_value="")
machine._handler.rescue_mode.side_effect = CallError(
request={"method": "GET", "uri": "www.example.com"},
response=Mock(status=HTTPStatus.FORBIDDEN),
content=content,
call="",
)
self.assertRaises(OperationNotAllowed, machine.enter_rescue_mode)
示例4: test_container_generate_upload_url_expiration
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def test_container_generate_upload_url_expiration(container, text_stream):
form_post = container.generate_upload_url(settings.TEXT_FORM_FILENAME, expires=1)
assert "url" in form_post and "fields" in form_post
assert uri_validator(form_post["url"])
sleep(1.1) # cannot generate a policy with -1 value
url = form_post["url"]
fields = form_post["fields"]
multipart_form_data = {"file": text_stream}
response = requests.post(url, data=fields, files=multipart_form_data)
if "s3" in container.driver.client._endpoint_url:
http_code = HTTPStatus.FORBIDDEN
else: # minio server
http_code = HTTPStatus.BAD_REQUEST
assert response.status_code == http_code, response.text
示例5: insert_role
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
"""Creates and inserts a new GSuite Admin Role.
Args:
name: str, the name of the new GSuite Admin Role.
customer_id: str, the G Suite customer ID to insert the role into.
Returns:
A dictionary object representing the new GSuite Admin Role.
https://developers.google.com/admin-sdk/directory/v1/reference/roles
Raises:
AlreadyExistsError: when the role with the provided name already exists.
ForbiddenError: when authorization fails.
InsertionError: when creation fails (e.g. failed to authenticate, improper
scopes, etc).
"""
try:
return self._client.roles().insert(
customer=customer_id,
body={
'roleName': name,
'rolePrivileges': _ROLE_PRIVILEGES,
'roleDescription': _ROLE_DESCRIPTION,
'isSystemRole': False,
'isSuperAdminRole': False,
},
).execute()
except errors.HttpError as err:
status = err.resp.status
if (status == http_status.CONFLICT or
status == http_status.INTERNAL_SERVER_ERROR):
raise AlreadyExistsError(
'role with name {!r} already exists'.format(name))
if status == http_status.FORBIDDEN:
raise ForbiddenError(_FORBIDDEN_ERROR_MSG)
logging.error(_INSERT_ROLE_ERROR_MSG, name, err)
raise InsertionError(_INSERT_ROLE_ERROR_MSG % (name, err))
示例6: login
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def login(request):
router = request.app.router
form = await request.post()
user_signature = (form['name'], form['password'])
# actually implement business logic to check user credentials
try:
user_id = DATABASE.index(user_signature)
# Always use `new_session` during login to guard against
# Session Fixation. See aiohttp-session#281
session = await new_session(request)
session['user_id'] = user_id
return web.HTTPFound(router['restricted'].url_for())
except ValueError:
return web.Response(text='No such user', status=HTTPStatus.FORBIDDEN)
示例7: forbidden
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def forbidden(self, response, **kwargs):
""" shortcuts to response 403 """
self.assertEqual(HTTPStatus.FORBIDDEN, response.status_code, "status code should be 403")
if kwargs:
self.assert_same(response.data, **kwargs)
return self
示例8: _parse_target_data
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def _parse_target_data(self, target_data):
"""
Validate the jsonapi payload for patch requests (to self.target):
- the payload must contain "id" and "type" keys.
- the type must match the target type
- an object with the specified id must exist
:param target_data: jsonapi instance payload
:return: sqla/safrs orm instance
"""
if not isinstance(target_data, dict):
raise ValidationError("Invalid data type {}".format(target_data))
target_id = target_data.get("id", None)
if target_id is None:
raise ValidationError("no target id {}".format(target_data))
target_type = target_data.get("type")
if not target_id:
raise ValidationError("Invalid id in data", HTTPStatus.FORBIDDEN)
if not target_type:
raise ValidationError("Invalid type in data", HTTPStatus.FORBIDDEN)
if target_type != self.target._s_type:
raise ValidationError("Invalid type {} != {}".format(target_type, self.target._s_type), HTTPStatus.FORBIDDEN)
target = self.target.get_instance(target_id)
if not target:
raise ValidationError("invalid target id {}".format(target_id))
return target
示例9: handle_status_code
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def handle_status_code(status_code):
logging.debug(f'Status code: {status_code}')
if status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationRequired()
if status_code == HTTPStatus.FORBIDDEN:
raise AccessDenied()
if status_code == HTTPStatus.SERVICE_UNAVAILABLE:
raise BackendNotAvailable()
if status_code >= 500:
raise BackendError()
if status_code >= 400:
raise UnknownError()
示例10: handle_exception
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def handle_exception():
"""
Context manager translating network related exceptions
to custom :mod:`~galaxy.api.errors`.
"""
try:
yield
except asyncio.TimeoutError:
raise BackendTimeout()
except aiohttp.ServerDisconnectedError:
raise BackendNotAvailable()
except aiohttp.ClientConnectionError:
raise NetworkError()
except aiohttp.ContentTypeError:
raise UnknownBackendResponse()
except aiohttp.ClientResponseError as error:
if error.status == HTTPStatus.UNAUTHORIZED:
raise AuthenticationRequired()
if error.status == HTTPStatus.FORBIDDEN:
raise AccessDenied()
if error.status == HTTPStatus.SERVICE_UNAVAILABLE:
raise BackendNotAvailable()
if error.status == HTTPStatus.TOO_MANY_REQUESTS:
raise TooManyRequests()
if error.status >= 500:
raise BackendError()
if error.status >= 400:
logging.warning(
"Got status %d while performing %s request for %s",
error.status, error.request_info.method, str(error.request_info.url)
)
raise UnknownError()
except aiohttp.ClientError:
logging.exception("Caught exception while performing request")
raise UnknownError()
示例11: roles_accepted
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def roles_accepted(*roles):
"""
Decorator which specifies that a user must have at least one of the
specified roles.
Aborts with HTTP: 403 if the user doesn't have at least one of the roles.
Example::
@app.route('/create_post')
@roles_accepted('ROLE_ADMIN', 'ROLE_EDITOR')
def create_post():
return 'Create Post'
The current user must have either the `ROLE_ADMIN` role or `ROLE_EDITOR`
role in order to view the page.
:param roles: The possible roles.
"""
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
perm = Permission(*[RoleNeed(role) for role in roles])
if not perm.can():
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated_view
return wrapper
示例12: roles_required
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def roles_required(*roles):
"""
Decorator which specifies that a user must have all the specified roles.
Aborts with HTTP 403: Forbidden if the user doesn't have the required roles.
Example::
@app.route('/dashboard')
@roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
def dashboard():
return 'Dashboard'
The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles
in order to view the page.
:param roles: The required roles.
"""
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
perms = [Permission(RoleNeed(role)) for role in roles]
for perm in perms:
if not perm.can():
abort(HTTPStatus.FORBIDDEN)
return fn(*args, **kwargs)
return decorated_view
return wrapper
示例13: _handle_view
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def _handle_view(self, name, **kwargs): # skipcq: PYL-W0613 (unused arg)
if not self.is_accessible():
if not user.is_authenticated:
return redirect(url_for('ADMIN_LOGIN_ENDPOINT', next=request.url))
abort(HTTPStatus.FORBIDDEN)
示例14: change_account
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def change_account(account_id: str, user: User):
permission_ok = False
new_token = b""
account = await AccountsService.get_account_by_id(
int(account_id), AccountsBackend()
)
if account:
permission_ok = await account.user_has_permission(user)
if permission_ok and account:
new_token = jwt_encode(user, account)
return web.json_response(data={"jwt": new_token.decode("utf-8")})
return web.json_response(status=HTTPStatus.FORBIDDEN)
示例15: test_http_status_to_canonical_code
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import FORBIDDEN [as 別名]
def test_http_status_to_canonical_code(self):
for status_code, expected in (
(HTTPStatus.OK, StatusCanonicalCode.OK),
(HTTPStatus.ACCEPTED, StatusCanonicalCode.OK),
(HTTPStatus.IM_USED, StatusCanonicalCode.OK),
(HTTPStatus.MULTIPLE_CHOICES, StatusCanonicalCode.OK),
(HTTPStatus.BAD_REQUEST, StatusCanonicalCode.INVALID_ARGUMENT),
(HTTPStatus.UNAUTHORIZED, StatusCanonicalCode.UNAUTHENTICATED),
(HTTPStatus.FORBIDDEN, StatusCanonicalCode.PERMISSION_DENIED),
(HTTPStatus.NOT_FOUND, StatusCanonicalCode.NOT_FOUND),
(
HTTPStatus.UNPROCESSABLE_ENTITY,
StatusCanonicalCode.INVALID_ARGUMENT,
),
(
HTTPStatus.TOO_MANY_REQUESTS,
StatusCanonicalCode.RESOURCE_EXHAUSTED,
),
(HTTPStatus.NOT_IMPLEMENTED, StatusCanonicalCode.UNIMPLEMENTED),
(HTTPStatus.SERVICE_UNAVAILABLE, StatusCanonicalCode.UNAVAILABLE),
(
HTTPStatus.GATEWAY_TIMEOUT,
StatusCanonicalCode.DEADLINE_EXCEEDED,
),
(
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
StatusCanonicalCode.INTERNAL,
),
(600, StatusCanonicalCode.UNKNOWN),
(99, StatusCanonicalCode.UNKNOWN),
):
with self.subTest(status_code=status_code):
actual = http_status_to_canonical_code(int(status_code))
self.assertEqual(actual, expected, status_code)