Python aiohttp.web.HTTPException() Examples

The following are 25 code examples of aiohttp.web.HTTPException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: middleware.py    From python-prometheus-demo with MIT License 6 votes vote down vote up
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 
Example #2
Source File: middlewares.py    From dvpwa with MIT License 6 votes vote down vote up
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 
Example #3
Source File: middlewares.py    From aiohttp_apiset with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: middlewares.py    From snare with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: middlewares.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: middleware.py    From chromewhip with MIT License 5 votes vote down vote up
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 
Example #7
Source File: server.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request, handler: _WebHandler
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #8
Source File: 01-login-session.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request, handler: _WebHandler
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #9
Source File: 01-error-middleware.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def error_middleware(
    request: web.Request,
    handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except asyncio.CancelledError:
        raise
    except Exception as ex:
        return aiohttp_jinja2.render_template(
            "error-page.html", request, {"error_text": str(ex)}, status=400
        ) 
Example #10
Source File: aiohttp_resources.py    From async-worker with MIT License 5 votes vote down vote up
def http_metrics_middleware(request: web.Request, handler: _Handler):
    start = now()
    try:
        metrics.requests_in_progress.labels(
            method=request.method, path=request.path
        ).inc()
        response = await handler(request)
        metrics.response_size.labels(
            method=request.method, path=request.path
        ).observe(response.content_length)
        metrics.request_duration.labels(
            method=request.method, path=request.path, status=response.status
        ).observe(now() - start)

        return response
    except web.HTTPException as e:
        metrics.request_duration.labels(
            method=request.method, path=request.path, status=e.status
        ).observe(now() - start)
        metrics.response_size.labels(
            method=request.method, path=request.path
        ).observe(e.content_length)
        raise e
    except Exception as e:
        metrics.request_duration.labels(
            method=request.method,
            path=request.path,
            status=HTTPStatus.INTERNAL_SERVER_ERROR,
        ).observe(now() - start)
        raise e
    finally:
        metrics.requests_in_progress.labels(
            method=request.method, path=request.path
        ).dec() 
Example #11
Source File: __init__.py    From mautrix-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def error_middleware(_, handler: Callable[[web.Request], Awaitable[web.Response]]
                               ) -> Callable[[web.Request], Awaitable[web.Response]]:
        async def middleware_handler(request: web.Request) -> web.Response:
            try:
                return await handler(request)
            except web.HTTPException as ex:
                return web.json_response({
                    "error": f"Unhandled HTTP {ex.status}",
                    "errcode": f"unhandled_http_{ex.status}",
                }, status=ex.status)

        return middleware_handler 
Example #12
Source File: handler.py    From transmute-core with MIT License 5 votes vote down vote up
def create_handler(transmute_func, context):

    @wraps(transmute_func.raw_func)
    async def handler(request):
        exc, result = None, None
        try:
            args, kwargs = await extract_params(request, context,
                                                transmute_func)
            result = await transmute_func.raw_func(*args, **kwargs)
        except HTTPException as hpe:
            code = hpe.status_code or 400
            exc = APIException(code=code, message=str(hpe))
        except Exception as e:
            exc = e
        if isinstance(result, web.Response):
            return result
        else:
            response = transmute_func.process_result(
                context, result, exc, request.content_type
            )
            return web.Response(
                body=response["body"], status=response["code"],
                content_type=response["content-type"],
                headers=response["headers"]
            )

    handler.transmute_func = transmute_func
    return handler 
Example #13
Source File: routes.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _wrap_error_handler(handler):
    @wraps(handler)
    async def inner(request):
        try:
            return await handler(request)
        except web.HTTPException as exc:
            headers = exc.headers
            headers.popall("Content-Type", None)
            return web.json_response(
                {"error": exc.reason}, headers=headers, status=exc.status
            )

    return inner 
Example #14
Source File: utils.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_data_from_response(response: Union[HTTPException, Response], config: Config, event_type: str):
    result = {}
    status = getattr(response, "status", getattr(response, "status_code", None))
    if isinstance(status, compat.integer_types):
        result["status_code"] = status
    if config.capture_headers and getattr(response, "headers", None):
        headers = response.headers
        result["headers"] = {key: ";".join(headers.getall(key)) for key in compat.iterkeys(headers)}
    return result 
Example #15
Source File: http.py    From tomodachi with MIT License 5 votes vote down vote up
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 
Example #16
Source File: routes.py    From dffml with MIT License 5 votes vote down vote up
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,
            ) 
Example #17
Source File: test_dispatcher.py    From aiohttp_apiset with Apache License 2.0 5 votes vote down vote up
def test_import_handler(hstr):
    handler, parameters = Route._import_handler(hstr)
    with pytest.raises(web.HTTPException):
        await handler(**{k: None for k in parameters}) 
Example #18
Source File: dispatcher.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
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"]) 
Example #19
Source File: route.py    From sockjs with Apache License 2.0 5 votes vote down vote up
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 
Example #20
Source File: route.py    From sockjs with Apache License 2.0 5 votes vote down vote up
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() 
Example #21
Source File: __init__.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
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 
Example #22
Source File: server.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: middleware.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: middleware.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def tracing_middleware(app):
    from elasticapm.contrib.aiohttp import CLIENT_KEY  # noqa

    async def handle_request(request, handler):
        elasticapm_client = app.get(CLIENT_KEY)
        if elasticapm_client:
            request[CLIENT_KEY] = elasticapm_client
            trace_parent = AioHttpTraceParent.from_headers(request.headers)
            elasticapm_client.begin_transaction("request", trace_parent=trace_parent)
            resource = request.match_info.route.resource
            name = request.method
            if resource:
                # canonical has been added in 3.3, and returns one of path, formatter, prefix
                for attr in ("canonical", "_path", "_formatter", "_prefix"):
                    if hasattr(resource, attr):
                        name += " " + getattr(resource, attr)
                        break
                else:
                    name += " unknown route"
            else:
                name += " unknown route"
            elasticapm.set_transaction_name(name, override=False)
            elasticapm.set_context(
                lambda: get_data_from_request(request, elasticapm_client.config, constants.TRANSACTION), "request"
            )

        try:
            response = await handler(request)
            elasticapm.set_transaction_result("HTTP {}xx".format(response.status // 100), override=False)
            elasticapm.set_context(
                lambda: get_data_from_response(response, elasticapm_client.config, constants.TRANSACTION), "response"
            )
            return response
        except Exception as exc:
            if elasticapm_client:
                elasticapm_client.capture_exception(
                    context={"request": get_data_from_request(request, elasticapm_client.config, constants.ERROR)}
                )
                elasticapm.set_transaction_result("HTTP 5xx", override=False)
                elasticapm.set_context({"status_code": 500}, "response")
                # some exceptions are response-like, e.g. have headers and status code. Let's try and capture them
                if isinstance(exc, (Response, HTTPException)):
                    elasticapm.set_context(
                        lambda: get_data_from_response(exc, elasticapm_client.config, constants.ERROR),  # noqa: F821
                        "response",
                    )

            raise
        finally:
            elasticapm_client.end_transaction()

    # decorating with @middleware is only required in aiohttp < 4.0, and we only support 3+
    if aiohttp.__version__.startswith("3"):
        return middleware(handle_request)
    return handle_request 
Example #25
Source File: server.py    From RPGBot with GNU General Public License v3.0 4 votes vote down vote up
def convert(self, request: web.Request):
        try:
            snowflake = int(request.match_info['snowflake'])
        except:
            raise web.HTTPBadRequest(reason="Malformed request")

        if request.method == "GET":
            logging.info(f"Received request to view info on bot {snowflake}")
            snowflake = int(snowflake)
            resp = dict((await self.get_botdata(snowflake))[0])
            return web.json_response(resp)
        else:
            try:
                if "Authorization" not in request.headers:
                    raise web.HTTPUnauthorized(reason="Failed to provide token!")  # Token was omitted from the headers

                token = request.headers["Authorization"]  # The user token
                snowflake = int(snowflake)  # The bot snowflake
                req = f"""SELECT * FROM userdata WHERE token = '{token.replace("'", "''")}';"""
                async with self.pool.acquire() as connection:
                    response = await connection.fetch(req)  # Get bots and webhook / gather type
                if response:
                    bots, type = response[0]["bots"], response[0]["type"]
                    if snowflake not in bots:  # That bot is not associated with that token
                        raise web.HTTPUnauthorized(reason="That snowflake is not valid!")

                    formdata = await request.post()

                    async with self.pool.acquire() as connection:
                        name = await connection.fetchval(
                            f"""SELECT name FROM botdata WHERE id = {snowflake};"""
                        )  # Get the bot's name
                        url = await connection.fetchval(
                            f"""SELECT url FROM botdata WHERE name = '{formdata["to_bot"].replace("'", "''")}';"""
                        )  # Get the URL of the bot we're sending to
                    if url is None:  # That bot is not in our database!
                        raise web.HTTPBadRequest(reason="That is an invalid bot!")

                    payload = {
                        "from_bot": name,
                        "amount": formdata["amount"],
                        "to_bot": formdata["to_bot"],
                        "server_id": formdata["server_id"]
                    }
                    dumped = json.dumps(payload, indent=4)

                    logging.info(f"Received request to convert {formdata['amount']} from {name} "
                                 f"to {formdata['to_bot']} on server {formdata['server_id']}")
                    if type is 0:  # If using webhooks
                        try:
                            await self.session.post(url, json=dumped)  # Post the payload to the other bot's URL
                        except Exception as e:
                            raise web.HTTPInternalServerError(reason="An error occurred forwarding to the bot!")

                    return web.json_response(payload)
                else:  # If we don't get a response from the given token, the token doesn't exist
                    raise web.HTTPUnauthorized(reason="Invalid token!")
            except web.HTTPException:
                raise
            except:  # Generic error catching, always gives 400 cause how could it be _my_ issue?
                return web.HTTPBadRequest(reason="An error occurred!")