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


Python web.middleware方法代码示例

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


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

示例1: get_session

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def get_session(request):
    session = request.get(SESSION_KEY)
    if session is None:
        storage = request.get(STORAGE_KEY)
        if storage is None:
            raise RuntimeError(
                "Install aiohttp_session middleware "
                "in your aiohttp.web.Application")
        else:
            session = await storage.load_session(request)
            if not isinstance(session, Session):
                raise RuntimeError(
                    "Installed {!r} storage should return session instance "
                    "on .load_session() call, got {!r}.".format(storage,
                                                                session))
            request[SESSION_KEY] = session
    return session 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:19,代码来源:__init__.py

示例2: create_error_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def create_error_middleware(self, overrides):

        @web.middleware
        async def error_middleware(request, handler):
            try:
                response = await handler(request)
                status = response.status
                override = overrides.get(status)
                if override:
                    response = await override(request)
                    response.headers.update(self.headers)
                    response.set_status(status)
                    return response
                return response
            except web.HTTPException as ex:
                override = overrides.get(ex.status)
                if override:
                    return await override(request)
                raise

        return error_middleware 
开发者ID:mushorg,项目名称:snare,代码行数:23,代码来源:middlewares.py

示例3: middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def middleware(self, request, handler):
        overrides = {}

        for elem in reversed(request.forwarded[-self._num:]):
            for_ = elem.get('for')
            if for_:
                overrides['remote'] = for_
            proto = elem.get('proto')
            if proto is not None:
                overrides['scheme'] = proto
            host = elem.get('host')
            if host is not None:
                overrides['host'] = host

        request = request.clone(**overrides)
        return await handler(request) 
开发者ID:aio-libs,项目名称:aiohttp-remotes,代码行数:18,代码来源:forwarded.py

示例4: middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def middleware(self, request, handler):
        try:
            overrides = {}
            headers = request.headers

            forwarded_for = self.get_forwarded_for(headers)
            if forwarded_for:
                overrides['remote'] = str(forwarded_for[-self._num])

            proto = self.get_forwarded_proto(headers)
            if proto:
                overrides['scheme'] = proto[-self._num]

            host = self.get_forwarded_host(headers)
            if host is not None:
                overrides['host'] = host

            request = request.clone(**overrides)

            return await handler(request)
        except RemoteError as exc:
            exc.log(request)
            await self.raise_error(request) 
开发者ID:aio-libs,项目名称:aiohttp-remotes,代码行数:25,代码来源:x_forwarded.py

示例5: setup

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def setup(self, app):
        if self._client is not None:  # pragma: no branch
            client = self._client
        else:
            client = aiohttp.ClientSession()  # pragma: no cover
        try:
            async with client.get(
                    'https://www.cloudflare.com/ips-v4') as response:
                self._ip_networks |= self._parse_mask(await response.text())
            async with client.get(
                    'https://www.cloudflare.com/ips-v6') as response:
                self._ip_networks |= self._parse_mask(await response.text())
        finally:
            if self._client is None:  # pragma: no cover
                await client.close()

        if not self._ip_networks:
            raise RuntimeError("No networks are available")
        app.middlewares.append(self.middleware) 
开发者ID:aio-libs,项目名称:aiohttp-remotes,代码行数:21,代码来源:cloudflare.py

示例6: error_pages_handler

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def error_pages_handler(self, overrides):
        @web.middleware
        async def middleware(request, handler):
            try:
                response = await handler(request)
                override = overrides.get(response.status)
                if override is None:
                    return response
                else:
                    return await override(request, response)
            except aiohttp.web.HTTPException as ex:
                override = overrides.get(ex.status)
                if override is None:
                    raise
                else:
                    return await override(request, ex)

        return middleware 
开发者ID:DevAlone,项目名称:proxy_py,代码行数:20,代码来源:proxy_provider_server.py

示例7: middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def middleware(self, request, handler):
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer'):
            token = token[7:]
        else:
            token = request.rel_url.query.get('token')
            if not token:
                token = request.headers.get('token')
        request.verified = False

        if token:
            try:
                payload = self.decode(token)
                request.verified = True
            except jwt.JWTError:
                raise web.HTTPUnauthorized()
        else:
            payload = {}
        request.session = payload
        return await handler(request) 
开发者ID:dvhb,项目名称:dvhb-hybrid,代码行数:22,代码来源:jwt.py

示例8: error_pages

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def error_pages(overrides):
    @web.middleware
    async def middleware(request, handler):
        try:
            response = await handler(request)
            override = overrides.get(response.status)
            if override is None:
                return response
            else:
                return await override(request, response)
        except web.HTTPException as ex:
            override = overrides.get(ex.status)
            if override is None:
                raise
            else:
                return await override(request, ex)

    return middleware 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:20,代码来源:middlewares.py

示例9: ratelimit

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def ratelimit(get_storage):
    @web.middleware
    async def ratelimit_middleware(request, handler):
        storage = get_storage(handler)
        if not hasattr(storage, "_ratelimit"):
            storage.setdefault("ratelimit", collections.defaultdict(lambda: 0))
            storage.setdefault("ratelimit_last", collections.defaultdict(lambda: 1))
            storage.setdefault("last_request", collections.defaultdict(lambda: 0))
        if storage["last_request"][request.remote] > time.time() - 30:
            # Maybe ratelimit, was requested within 30 seconds
            last = storage["ratelimit_last"][request.remote]
            storage["ratelimit_last"][request.remote] = storage["ratelimit"][request.remote]
            storage["ratelimit"][request.remote] += last
            if storage["ratelimit"][request.remote] > 50:
                # If they have to wait more than 5 seconds (10 requests), kill em.
                return web.Response(status=429)
            await asyncio.sleep(storage["ratelimit"][request.remote] / 10)
        else:
            try:
                del storage["ratelimit"][request.remote]
                del storage["ratelimit_last"][request.remote]
            except KeyError:
                pass
        storage["last_request"][request.remote] = time.time()
        return await handler(request)
    return ratelimit_middleware 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:28,代码来源:core.py

示例10: setup_management_ui

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def setup_management_ui(self) -> None:
        ui_base = self.config["server.ui_base_path"]
        if ui_base == "/":
            ui_base = ""
        directory = (self.config["server.override_resource_path"]
                     or pkg_resources.resource_filename("maubot", "management/frontend/build"))
        self.app.router.add_static(f"{ui_base}/static", f"{directory}/static")
        self.setup_static_root_files(directory, ui_base)

        with open(f"{directory}/index.html", "r") as file:
            index_html = file.read()

        @web.middleware
        async def frontend_404_middleware(request: web.Request, handler) -> web.Response:
            if hasattr(handler, "__self__") and isinstance(handler.__self__, web.StaticResource):
                try:
                    return await handler(request)
                except web.HTTPNotFound:
                    return web.Response(body=index_html, content_type="text/html")
            return await handler(request)

        async def ui_base_redirect(_: web.Request) -> web.Response:
            raise web.HTTPFound(f"{ui_base}/")

        self.app.middlewares.append(frontend_404_middleware)
        self.app.router.add_get(f"{ui_base}/", lambda _: web.Response(body=index_html,
                                                                      content_type="text/html"))
        self.app.router.add_get(ui_base, ui_base_redirect) 
开发者ID:maubot,项目名称:maubot,代码行数:30,代码来源:server.py

示例11: rlim_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def rlim_middleware(app: web.Application,
                          request: web.Request,
                          handler: WebRequestHandler) -> web.StreamResponse:
    # This is a global middleware: request.app is the root app.
    now = Decimal(time.time()).quantize(_time_prec)
    rr = app['redis_rlim']
    if request['is_authorized']:
        rate_limit = request['keypair']['rate_limit']
        access_key = request['keypair']['access_key']
        ret = await redis.execute_script(
            rr, 'ratelimit', _rlim_script,
            [access_key],
            [str(now), str(_rlim_window)],
        )
        rolling_count = int(ret)
        if rolling_count > rate_limit:
            raise RateLimitExceeded
        remaining = rate_limit - rolling_count
        response = await handler(request)
        response.headers['X-RateLimit-Limit'] = str(rate_limit)
        response.headers['X-RateLimit-Remaining'] = str(remaining)
        response.headers['X-RateLimit-Window'] = str(_rlim_window)
        return response
    else:
        # No checks for rate limiting for non-authorized queries.
        response = await handler(request)
        response.headers['X-RateLimit-Limit'] = '1000'
        response.headers['X-RateLimit-Remaining'] = '1000'
        response.headers['X-RateLimit-Window'] = str(_rlim_window)
        return response 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:32,代码来源:ratelimit.py

示例12: create_app

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def create_app(default_cors_options: CORSOptions) -> Tuple[web.Application, Iterable[WebMiddleware]]:
    app = web.Application()
    app['api_versions'] = (1, 2, 3, 4)
    app.on_startup.append(init)
    app.on_shutdown.append(shutdown)
    # middleware must be wrapped by web.middleware at the outermost level.
    return app, [web.middleware(apartial(rlim_middleware, app))] 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:9,代码来源:ratelimit.py

示例13: new_session

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def new_session(request):
    storage = request.get(STORAGE_KEY)
    if storage is None:
        raise RuntimeError(
            "Install aiohttp_session middleware "
            "in your aiohttp.web.Application")
    else:
        session = await storage.new_session()
        if not isinstance(session, Session):
            raise RuntimeError(
                "Installed {!r} storage should return session instance "
                "on .load_session() call, got {!r}.".format(storage, session))
        request[SESSION_KEY] = session
    return session 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:16,代码来源:__init__.py

示例14: session_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def session_middleware(storage):

    if not isinstance(storage, AbstractStorage):
        raise RuntimeError("Expected AbstractStorage got {}".format(storage))

    @web.middleware
    async def factory(request, handler):
        request[STORAGE_KEY] = storage
        raise_response = False
        try:
            response = await handler(request)
        except web.HTTPException as exc:
            response = exc
            raise_response = True
        if not isinstance(response, web.StreamResponse):
            raise RuntimeError(
                "Expect response, not {!r}".format(type(response)))
        if not isinstance(response, web.Response):
            # likely got websocket or streaming
            return response
        if response.prepared:
            raise RuntimeError(
                "Cannot save session data into prepared response")
        session = request.get(SESSION_KEY)
        if session is not None:
            if session._changed:
                await storage.save_session(request, response, session)
        if raise_response:
            raise response
        return response

    return factory 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:34,代码来源:__init__.py

示例15: test_validation_exception_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import middleware [as 别名]
def test_validation_exception_middleware(swagger_docs, aiohttp_client):
    @web.middleware
    async def middleware(request, handler):
        try:
            return await handler(request)
        except RequestValidationFailed as exc:
            assert exc.errors == {"query": "value should be type of int"}
            raise exc

    async def handler(request):
        """
        ---
        parameters:

          - name: query
            in: query
            required: true
            schema:
              type: integer

        responses:
          '200':
            description: OK.
        """
        return web.json_response()

    swagger = swagger_docs()
    swagger._app.middlewares.append(middleware)
    swagger.add_get("/r", handler)

    client = await aiohttp_client(swagger._app)

    params = {"query": "abc"}
    resp = await client.get("/r", params=params)
    assert resp.status == 400 
开发者ID:hh-h,项目名称:aiohttp-swagger3,代码行数:37,代码来源:test_middleware.py


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