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


Python web.HTTPException方法代码示例

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


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

示例1: __call__

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def __call__(self, app, handler):
        async def process(request):
            try:
                response = await handler(request)
            except web.HTTPException as ex:
                return self.resolve_exception(ex)
            else:
                if isinstance(response, asyncio.Future):
                    response = await response
                if isinstance(response, dict):
                    status = response.get('status', 200)
                    if not isinstance(status, int):
                        status = 200
                    return self.response(response, status=status)
                elif not isinstance(response, web.StreamResponse):
                    return self.response(response)
                return response
        return process 
开发者ID:aamalev,项目名称:aiohttp_apiset,代码行数:20,代码来源:middlewares.py

示例2: create_error_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [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: error_pages

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def error_pages(overrides):
    async def middleware(app, handler):
        async def middleware_handler(request):
            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_handler
    return middleware 
开发者ID:DataDog,项目名称:trace-examples,代码行数:20,代码来源:middlewares.py

示例4: error_pages

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [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

示例5: error_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def error_middleware(app, handler):

    @asyncio.coroutine
    def middleware_handler(request):
        try:
            response = yield from handler(request)
            return response
        except web.HTTPException as ex:
            resp = web.Response(body=str(ex), status=ex.status)
            return resp
        except Exception as ex:
            resp = web.Response(body=str(ex), status=500)
            return resp



    return middleware_handler 
开发者ID:amitsaha,项目名称:python-prometheus-demo,代码行数:19,代码来源:middleware.py

示例6: get_http_response_status

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def get_http_response_status(value: Union[str, bytes, Dict, List, Tuple, web.Response, Response, Exception], request: Optional[web.Request] = None, verify_transport: bool = True) -> Optional[int]:
    if isinstance(value, Exception) or isinstance(value, web.HTTPException):
        status_code = int(getattr(value, 'status', 500)) if value is not None else 500
        return status_code
    else:
        response = await resolve_response(value, request=request)
        status_code = int(response.status) if response is not None else 500
        if verify_transport and request is not None and request.transport is None:
            return 499
        else:
            return status_code 
开发者ID:kalaspuff,项目名称:tomodachi,代码行数:13,代码来源:http.py

示例7: error

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def error(request: web.Request, handler: Handler) -> web.Response:
    try:
        return await handler(request)
    except web.HTTPException as ex:
        if ex.status_code == 404:
            return resp.path_not_found
        elif ex.status_code == 405:
            return resp.method_not_allowed
        return web.json_response({
            "error": f"Unhandled HTTP {ex.status}",
            "errcode": f"unhandled_http_{ex.status}",
        }, status=ex.status)
    except Exception:
        log.exception("Error in handler")
        return resp.internal_server_error 
开发者ID:maubot,项目名称:maubot,代码行数:17,代码来源:middleware.py

示例8: exception_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def exception_middleware(request: web.Request,
                               handler: WebRequestHandler) -> web.StreamResponse:
    app = request.app
    error_monitor = app['error_monitor']
    stats_monitor = app['stats_monitor']
    try:
        await stats_monitor.report_metric(INCREMENT, 'ai.backend.gateway.api.requests')
        resp = (await handler(request))
    except BackendError as ex:
        if ex.status_code == 500:
            log.exception('Internal server error raised inside handlers')
            raise
        await error_monitor.capture_exception()
        await stats_monitor.report_metric(INCREMENT, 'ai.backend.gateway.api.failures')
        await stats_monitor.report_metric(INCREMENT, f'ai.backend.gateway.api.status.{ex.status_code}')
        raise
    except web.HTTPException as ex:
        await stats_monitor.report_metric(INCREMENT, 'ai.backend.gateway.api.failures')
        await stats_monitor.report_metric(INCREMENT, f'ai.backend.gateway.api.status.{ex.status_code}')
        if ex.status_code == 404:
            raise GenericNotFound
        if ex.status_code == 405:
            concrete_ex = cast(web.HTTPMethodNotAllowed, ex)
            raise MethodNotAllowed(concrete_ex.method, concrete_ex.allowed_methods)
        log.warning('Bad request: {0!r}', ex)
        raise GenericBadRequest
    except asyncio.CancelledError as e:
        # The server is closing or the client has disconnected in the middle of
        # request.  Atomic requests are still executed to their ends.
        log.debug('Request cancelled ({0} {1})', request.method, request.rel_url)
        raise e
    except Exception as e:
        await error_monitor.capture_exception()
        log.exception('Uncaught exception in HTTP request handlers {0!r}', e)
        if app['config']['debug']['enabled']:
            raise InternalServerError(traceback.format_exc())
        else:
            raise InternalServerError()
    else:
        await stats_monitor.report_metric(INCREMENT, f'ai.backend.gateway.api.status.{resp.status}')
        return resp 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:43,代码来源:server.py

示例9: session_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [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

示例10: handler

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

        # lookup transport
        tid = info["transport"]

        if tid not in self.handlers or tid in self.disable_transports:
            return web.HTTPNotFound()

        create, transport = self.handlers[tid]

        # session
        manager = self.manager
        if not manager.started:
            manager.start()

        sid = info["session"]
        if not sid or "." in sid or "." in info["server"]:
            return web.HTTPNotFound()

        try:
            session = manager.get(sid, create, request=request)
        except KeyError:
            return web.HTTPNotFound(headers=session_cookie(request))

        t = transport(manager, session, request)
        try:
            return await t.process()
        except asyncio.CancelledError:
            raise
        except web.HTTPException as exc:
            return exc
        except Exception:
            log.exception("Exception in transport: %s" % tid)
            if manager.is_acquired(session):
                await manager.release(session)
            return web.HTTPInternalServerError() 
开发者ID:aio-libs,项目名称:sockjs,代码行数:39,代码来源:route.py

示例11: websocket

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def websocket(self, request):
        # session
        sid = "%0.9d" % random.randint(1, 2147483647)
        session = self.manager.get(sid, True, request=request)

        transport = RawWebSocketTransport(self.manager, session, request)
        try:
            return await transport.process()
        except asyncio.CancelledError:
            raise
        except web.HTTPException as exc:
            return exc 
开发者ID:aio-libs,项目名称:sockjs,代码行数:14,代码来源:route.py

示例12: log_task

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def log_task(self, task: CompletedTask):
        """Log a completed task using the stats collector."""
        if task.exc_info and not issubclass(task.exc_info[0], HTTPException):
            # skip errors intentionally returned to HTTP clients
            LOGGER.exception(
                "Handler error: %s", task.ident or "", exc_info=task.exc_info
            )
        if self.collector:
            timing = task.timing
            if "queued" in timing:
                self.collector.log(
                    "Dispatcher:queued", timing["unqueued"] - timing["queued"]
                )
            if task.ident:
                self.collector.log(task.ident, timing["ended"] - timing["started"]) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:17,代码来源:dispatcher.py

示例13: test_import_handler

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def test_import_handler(hstr):
    handler, parameters = Route._import_handler(hstr)
    with pytest.raises(web.HTTPException):
        await handler(**{k: None for k in parameters}) 
开发者ID:aamalev,项目名称:aiohttp_apiset,代码行数:6,代码来源:test_dispatcher.py

示例14: error_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def error_middleware(self, request, handler):
        try:
            # HACK This checks if aiohttp's builtin not found handler is going
            # to be called
            # Check if handler is the not found handler
            if "Not Found" in str(handler):
                # Run get_registered_handler to see if we can find the handler
                new_handler = await self.get_registered_handler(request)
                if new_handler is not None:
                    handler = new_handler
            return await handler(request)
        except web.HTTPException as error:
            response = {"error": error.reason}
            if error.text is not None:
                response["error"] = error.text
            return web.json_response(response, status=error.status)
        except Exception as error:  #  pragma: no cov
            self.logger.error(
                "ERROR handling %s: %s",
                request,
                traceback.format_exc().strip(),
            )
            return web.json_response(
                {"error": "Internal Server Error"},
                status=HTTPStatus.INTERNAL_SERVER_ERROR,
            ) 
开发者ID:intel,项目名称:dffml,代码行数:28,代码来源:routes.py

示例15: error_middleware

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPException [as 别名]
def error_middleware(app, handler):
    async def middleware_handler(request):
        try:
            response = await handler(request)
            if response.status != 200:
                return json_error(response.message)
            return response
        except web.HTTPException as ex:
            return json_error(ex.reason)
        except ChromewhipException as ex:
            return json_error(ex.args[0])
        except Exception as ex:
            verbose_tb = traceback.format_exc()
            return json_error(verbose_tb)
    return middleware_handler 
开发者ID:chuckus,项目名称:chromewhip,代码行数:17,代码来源:middleware.py


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