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


Python HTTPStatus.FORBIDDEN属性代码示例

本文整理汇总了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 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:25,代码来源:anonymous_user_required.py

示例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 
开发者ID:briancappello,项目名称:flask-react-spa,代码行数:19,代码来源:decorators.py

示例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) 
开发者ID:maas,项目名称:python-libmaas,代码行数:19,代码来源:test_machines.py

示例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 
开发者ID:scottwernervt,项目名称:cloudstorage,代码行数:20,代码来源:test_drivers_minio.py

示例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)) 
开发者ID:google,项目名称:loaner,代码行数:43,代码来源:directory.py

示例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) 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:17,代码来源:login_required_example.py

示例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 
开发者ID:zaihui,项目名称:hutils,代码行数:8,代码来源:unittest.py

示例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 
开发者ID:thomaxxl,项目名称:safrs,代码行数:28,代码来源:jsonapi.py

示例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() 
开发者ID:bartok765,项目名称:galaxy_blizzard_plugin,代码行数:14,代码来源:backend.py

示例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() 
开发者ID:TouwaStar,项目名称:Galaxy_Plugin_Bethesda,代码行数:37,代码来源:http.py

示例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 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:30,代码来源:roles_accepted.py

示例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 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:30,代码来源:roles_required.py

示例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) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:7,代码来源:security.py

示例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) 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:17,代码来源:accounts.py

示例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) 
开发者ID:open-telemetry,项目名称:opentelemetry-python,代码行数:36,代码来源:test_utils.py


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