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


Python web.HTTPForbidden方法代码示例

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


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

示例1: getguild

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def getguild(self, request: web.Request):
        guild = int(request.match_info['guild'])
        req = f"""SELECT info FROM guilddata WHERE UUID = $1"""
        async with self.bot.db._conn.acquire() as connection:
            response = await connection.fetchval(req, guild)
        if response:
            data = json.loads(response)

            fdata = data
            if request.match_info['tail']:
                for item in request.match_info['tail'].split("/"):
                    if not item:
                        continue
                    try:
                        key = unquote(item)
                        if isinstance(fdata, list):
                            key = int(key)
                        fdata = fdata[key]
                    except:
                        raise web.HTTPNotFound()

            return web.json_response(fdata)
        raise web.HTTPForbidden()

    # @server.route("/", methods=["GET"]) 
开发者ID:henry232323,项目名称:RPGBot,代码行数:27,代码来源:server.py

示例2: test_403_not_captured

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_403_not_captured(sentry_init, aiohttp_client, loop, capture_events):
    sentry_init(integrations=[AioHttpIntegration()])

    async def hello(request):
        raise web.HTTPForbidden()

    app = web.Application()
    app.router.add_get("/", hello)

    events = capture_events()

    client = await aiohttp_client(app)
    resp = await client.get("/")
    assert resp.status == 403

    assert not events 
开发者ID:getsentry,项目名称:sentry-python,代码行数:18,代码来源:test_aiohttp.py

示例3: check_permission

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def check_permission(request, permission, context=None):
    """Checks permissions

    Custom implementation replacing aiohttp-security one. This one
    adds the requested permissions to the request so they can
    be presented in the error handler.

    Raises:
      HTTPForbidden
    """

    await check_authorized(request)
    allowed = await permits(request, permission, context)
    if not allowed:
        request['permission_required'] = permission
        raise web.HTTPForbidden() 
开发者ID:bioconda,项目名称:bioconda-utils,代码行数:18,代码来源:views.py

示例4: rotate_public_did_keypair

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def rotate_public_did_keypair(request: web.BaseRequest):
    """
    Request handler for rotating key pair associated with public DID.

    Args:
        request: aiohttp request object
    """
    context = request.app["request_context"]
    ledger = await context.inject(BaseLedger, required=False)
    if not ledger:
        reason = "No ledger available"
        if not context.settings.get_value("wallet.type"):
            reason += ": missing wallet-type?"
        raise web.HTTPForbidden(reason=reason)
    async with ledger:
        try:
            await ledger.rotate_public_did_keypair()  # do not take seed over the wire
        except (WalletError, BadLedgerRequestError) as err:
            raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({}) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:23,代码来源:routes.py

示例5: actionmenu_perform

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def actionmenu_perform(request: web.BaseRequest):
    """
    Request handler for performing a menu action.

    Args:
        request: aiohttp request object

    """
    context = request.app["request_context"]
    connection_id = request.match_info["conn_id"]
    outbound_handler = request.app["outbound_message_router"]
    params = await request.json()

    try:
        connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
    except StorageNotFoundError as err:
        raise web.HTTPNotFound(reason=err.roll_up) from err

    if connection.is_ready:
        msg = Perform(name=params["name"], params=params.get("params"))
        await outbound_handler(msg, connection_id=connection_id)
        return web.json_response({})

    raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready") 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:26,代码来源:routes.py

示例6: actionmenu_request

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def actionmenu_request(request: web.BaseRequest):
    """
    Request handler for requesting a menu from the connection target.

    Args:
        request: aiohttp request object

    """
    context = request.app["request_context"]
    connection_id = request.match_info["conn_id"]
    outbound_handler = request.app["outbound_message_router"]

    try:
        connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
    except StorageNotFoundError as err:
        LOGGER.debug("Connection not found for action menu request: %s", connection_id)
        raise web.HTTPNotFound(reason=err.roll_up) from err

    if connection.is_ready:
        msg = MenuRequest()
        await outbound_handler(msg, connection_id=connection_id)
        return web.json_response({})

    raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready") 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:26,代码来源:routes.py

示例7: wallet_create_did

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def wallet_create_did(request: web.BaseRequest):
    """
    Request handler for creating a new local DID in the wallet.

    Args:
        request: aiohttp request object

    Returns:
        The DID info

    """
    context = request.app["request_context"]
    wallet: BaseWallet = await context.inject(BaseWallet, required=False)
    if not wallet:
        raise web.HTTPForbidden(reason="No wallet available")
    try:
        info = await wallet.create_local_did()
    except WalletError as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({"result": format_did_info(info)}) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:23,代码来源:routes.py

示例8: test_missing_wallet

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_missing_wallet(self):
        request = async_mock.MagicMock()
        request.app = self.app
        self.context.injector.clear_binding(BaseWallet)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_create_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_did_list(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_get_public_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_set_public_did(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_set_did_endpoint(request)

        with self.assertRaises(HTTPForbidden):
            await test_module.wallet_get_did_endpoint(request) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:24,代码来源:test_routes.py

示例9: test_set_did_endpoint_public_did_no_ledger

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_set_did_endpoint_public_did_no_ledger(self):
        request = async_mock.MagicMock()
        request.app = self.app
        request.json = async_mock.CoroutineMock(
            return_value={
                "did": self.test_did,
                "endpoint": "https://my-endpoint.ca:8020",
            }
        )

        self.wallet.get_local_did.return_value = DIDInfo(
            self.test_did,
            self.test_verkey,
            {"public": False, "endpoint": "http://old-endpoint.ca"},
        )
        self.wallet.get_public_did.return_value = DIDInfo(
            self.test_did, self.test_verkey, {}
        )

        with self.assertRaises(test_module.web.HTTPForbidden):
            await test_module.wallet_set_did_endpoint(request) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:23,代码来源:test_routes.py

示例10: check_token

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def check_token(self, request: web.Request) -> Optional['u.User']:
        try:
            token = request.headers["Authorization"]
            token = token[len("Bearer "):]
        except KeyError:
            raise web.HTTPBadRequest(body='{"error": "Missing Authorization header"}',
                                     headers=self._headers)
        except IndexError:
            raise web.HTTPBadRequest(body='{"error": "Malformed Authorization header"}',
                                     headers=self._headers)
        if self.shared_secret and token == self.shared_secret:
            try:
                user_id = request.query["user_id"]
            except KeyError:
                raise web.HTTPBadRequest(body='{"error": "Missing user_id query param"}',
                                         headers=self._headers)
        else:
            user_id = self.verify_token(token)
            if not user_id:
                raise web.HTTPForbidden(body='{"error": "Invalid token"}', headers=self._headers)

        user = u.User.get_by_mxid(user_id)
        return user 
开发者ID:tulir,项目名称:mautrix-facebook,代码行数:25,代码来源:public.py

示例11: ensure_request_allowed

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def ensure_request_allowed(request, conf):
    if is_request_allowed(request, conf):
        return
    if conf.allowed_origin:
        log.warning(
            "API requests with Origin '%s' are not allowed, "
            "configuration 'allowed_origin' limits requests to: '%s'",
            request.headers.get('Origin'), conf.allowed_origin
        )
    else:
        log.warning(
            "API requests with Origin '%s' are not allowed, "
            "update configuration 'allowed_origin' to enable this origin.",
            request.headers.get('Origin')
        )
    raise web.HTTPForbidden() 
开发者ID:lbryio,项目名称:lbry-sdk,代码行数:18,代码来源:security.py

示例12: _parse_request_headers

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def _parse_request_headers(request: web.Request):
        """Parse Access-Control-Request-Headers header or the preflight request

        Returns set of headers in upper case.
        """
        headers = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
        if headers is None:
            return frozenset()

        # FIXME: validate each header string, if parsing fails, raise
        # HTTPForbidden.
        # FIXME: check, that headers split and stripped correctly (according
        # to ABNF).
        headers = (h.strip(" \t").upper() for h in headers.split(","))
        # pylint: disable=bad-builtin
        return frozenset(filter(None, headers)) 
开发者ID:aio-libs,项目名称:aiohttp-cors,代码行数:18,代码来源:preflight_handler.py

示例13: adapt_cluster

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def adapt_cluster(request):
    user = request["user"]
    cluster_name = request.match_info["cluster_name"]
    backend = request.app["backend"]
    cluster = await backend.get_cluster(cluster_name)
    if cluster is None:
        raise web.HTTPNotFound(reason=f"Cluster {cluster_name} not found")
    if not user.has_permissions(cluster):
        raise web.HTTPForbidden(
            reason=f"User {user.name} lacks permissions to view cluster {cluster_name}"
        )

    msg = await request.json()
    minimum = msg.get("minimum", None)
    maximum = msg.get("maximum", None)
    active = msg.get("active", True)

    try:
        await backend.forward_message_to_scheduler(
            cluster,
            {"op": "adapt", "minimum": minimum, "maximum": maximum, "active": active},
        )
    except PublicException as exc:
        raise web.HTTPConflict(reason=str(exc))
    return web.Response() 
开发者ID:dask,项目名称:dask-gateway,代码行数:27,代码来源:routes.py

示例14: user_login

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def user_login(request, email, password, connection=None):
    models = request.app.models
    user = await models.user.get_user_by_email(email, connection=connection)
    if user:
        if not user.is_active:
            raise web.HTTPForbidden(reason="User disabled")
        elif check_password(password, user.password):
            await models.user_action_log_entry.create_login(
                request, user_id=user.pk, connection=connection)
            token = request.app.context.jwt.generate(uid=user.id)
            return web.json_response(
                {
                    'uid': user.id,
                    'profile': await user.get_profile(connection=connection),
                    'token': token,
                }, headers={'Authorization': 'Bearer %s' % token},
            )
    raise web.HTTPUnauthorized(reason="Login incorrect") 
开发者ID:dvhb,项目名称:dvhb-hybrid,代码行数:20,代码来源:jwt.py

示例15: static_request_handler

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def static_request_handler(cls: Any, obj: Any, context: Dict, func: Any, path: str, base_url: str, ignore_logging: Union[bool, List[int], Tuple[int]] = False) -> Any:
        if '?P<filename>' not in base_url:
            pattern = r'^{}(?P<filename>.+?)$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
        else:
            pattern = r'^{}$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
        compiled_pattern = re.compile(pattern)

        if path.startswith('/'):
            path = os.path.dirname(path)
        else:
            path = '{}/{}'.format(os.path.dirname(context.get('context', {}).get('_service_file_path')), path)

        if not path.endswith('/'):
            path = '{}/'.format(path)

        async def handler(request: web.Request) -> web.Response:
            result = compiled_pattern.match(request.path)
            filename = result.groupdict()['filename'] if result else ''
            filepath = '{}{}'.format(path, filename)

            try:
                if os.path.commonprefix((os.path.realpath(filepath), os.path.realpath(path))) != os.path.realpath(path) or os.path.isdir(filepath) or not os.path.exists(filepath):
                    raise web.HTTPNotFound()  # type: ignore

                pathlib.Path(filepath).open('r')

                response = FileResponse(path=filepath,  # type: ignore
                                        chunk_size=256 * 1024)  # type: web.Response
                return response
            except PermissionError as e:
                raise web.HTTPForbidden()  # type: ignore

        route_context = {'ignore_logging': ignore_logging}
        context['_http_routes'] = context.get('_http_routes', [])
        context['_http_routes'].append(('GET', pattern, handler, route_context))

        start_func = cls.start_server(obj, context)
        return (await start_func) if start_func else None 
开发者ID:kalaspuff,项目名称:tomodachi,代码行数:40,代码来源:http.py


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