Python aiohttp.web.HTTPInternalServerError() Examples

The following are 28 code examples of aiohttp.web.HTTPInternalServerError(). 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: test_route.py    From sockjs with Apache License 2.0 6 votes vote down vote up
def test_release_session_for_failed_transport(make_route, make_request):
    request = make_request(
        "GET",
        "/sm/",
        match_info={"transport": "test", "session": "s1", "server": "000"},
    )

    class Transport:
        def __init__(self, manager, session, request):
            self.manager = manager
            self.session = session

        async def process(self):
            await self.manager.acquire(self.session)
            raise Exception("Error")

    route = make_route(handlers={"test": (True, Transport)})
    res = await route.handler(request)
    assert isinstance(res, web.HTTPInternalServerError)

    s1 = route.manager["s1"]
    assert not route.manager.is_acquired(s1) 
Example #2
Source File: conftest.py    From aiozipkin with Apache License 2.0 6 votes vote down vote up
def spans_handler(self, request: web.Request) -> web.Response:
        if len(self.next_errors) > 0:
            err = self.next_errors.pop(0)
            if err == 'disconnect':
                request.transport.close()
                await asyncio.sleep(1, loop=self._loop)
            elif err == 'timeout':
                await asyncio.sleep(60, loop=self._loop)
            return web.HTTPInternalServerError()

        data = await request.json()
        if self._wait_count is not None:
            self._wait_count -= 1
        self._received_data.append(data)
        if self._wait_fut is not None and self._wait_count == 0:
            self._wait_fut.set_result(None)

        return aiohttp.web.Response(text='', status=200) 
Example #3
Source File: api.py    From aiohttp-security with Apache License 2.0 6 votes vote down vote up
def remember(request, response, identity, **kwargs):
    """Remember identity into response.

    The action is performed by identity_policy.remember()

    Usually the identity is stored in user cookies somehow but may be
    pushed into custom header also.
    """
    assert isinstance(identity, str), identity
    assert identity
    identity_policy = request.config_dict.get(IDENTITY_KEY)
    if identity_policy is None:
        text = ("Security subsystem is not initialized, "
                "call aiohttp_security.setup(...) first")
        # in order to see meaningful exception message both: on console
        # output and rendered page we add same message to *reason* and
        # *text* arguments.
        raise web.HTTPInternalServerError(reason=text, text=text)
    await identity_policy.remember(request, response, identity, **kwargs) 
Example #4
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 6 votes vote down vote up
def test_template_not_mapping():

    @aiohttp_mako.template('tmpl.html')
    async def func(request):
        return 'data'

    app = web.Application()
    lookup = aiohttp_mako.setup(app, input_encoding='utf-8',
                                output_encoding='utf-8',
                                default_filters=['decode.utf8'])

    tplt = "<html><body><h1>${head}</h1>${text}</body></html>"
    lookup.put_string('tmpl.html', tplt)

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert "context should be mapping, not" \
           " <class 'str'>" == ctx.value.text 
Example #5
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 6 votes vote down vote up
def test_render_not_initialized():

    async def func(request):
        return aiohttp_mako.render_template('template', request, {})

    app = web.Application()
    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert "Template engine is not initialized, " \
        "call aiohttp_mako.setup(app_key={}) first" \
        "".format(aiohttp_mako.APP_KEY) == ctx.value.text 
Example #6
Source File: test_route.py    From sockjs with Apache License 2.0 6 votes vote down vote up
def test_fail_transport(make_route, make_request):
    request = make_request(
        "GET",
        "/sm/",
        match_info={"transport": "test", "session": "session", "server": "000"},
    )

    params = []

    class Transport:
        def __init__(self, manager, session, request):
            params.append((manager, session, request))

        def process(self):
            raise Exception("Error")

    route = make_route(handlers={"test": (True, Transport)})
    res = await route.handler(request)
    assert isinstance(res, web.HTTPInternalServerError) 
Example #7
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_mapping():

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return 123

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': 'tmpl'}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "context should be mapping, not <class 'int'>"
    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #8
Source File: session.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def restart(request: web.Request) -> web.Response:
    registry = request.app['registry']
    session_name = request.match_info['session_name']
    requester_access_key, owner_access_key = await get_access_key_scopes(request)
    log.info('RESTART (ak:{0}/{1}, s:{2})',
             requester_access_key, owner_access_key, session_name)
    try:
        await registry.increment_session_usage(session_name, owner_access_key)
        await registry.restart_session(session_name, owner_access_key)
    except BackendError:
        log.exception('RESTART: exception')
        raise
    except:
        await request.app['error_monitor'].capture_exception(user=request['user']['uuid'])
        log.exception('RESTART: unexpected error')
        raise web.HTTPInternalServerError
    return web.Response(status=204) 
Example #9
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_initialized():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "Template engine is not initialized, " \
          "call aiohttp_jinja2.setup(..., app_key={}" \
          ") first".format(aiohttp_jinja2.APP_KEY)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #10
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_template_not_found():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    t = "Template 'template' not found"
    assert t == ctx.value.text
    assert t == ctx.value.reason 
Example #11
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 5 votes vote down vote up
def test_template_not_found():

    app = web.Application()
    aiohttp_mako.setup(app, input_encoding='utf-8',
                       output_encoding='utf-8',
                       default_filters=['decode.utf8'])

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        aiohttp_mako.render_template('template', req, {})

    assert "Template 'template' not found" == ctx.value.text 
Example #12
Source File: natriumcast.py    From natrium-wallet-server with MIT License 5 votes vote down vote up
def http_api(r: web.Request):
    try:
        request_json = await r.json()
        reply = await handle_user_message(r, json.dumps(request_json))
        if reply is not None:
            return web.json_response(data=json.loads(reply))
        else:
            return web.json_response(data={'error':'bad request'})
    except Exception:
        log.server_logger.exception("received exception in http_api")
        return web.HTTPInternalServerError(reason=f"Something went wrong {str(sys.exc_info())}") 
Example #13
Source File: auth.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def authenticate(self, request):
        token = self.get_token(request)
        if token is None:
            raise unauthorized("jupyterhub")

        url = "%s/authorizations/token/%s" % (
            self.jupyterhub_api_url,
            quote(token, safe=""),
        )

        kwargs = {
            "headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
            "ssl": self.ssl_context,
        }

        resp = await self.session.get(url, **kwargs)

        if resp.status < 400:
            data = await resp.json()
            return User(data["name"], groups=data["groups"], admin=data["admin"])
        elif resp.status == 404:
            self.log.debug("Token for non-existant user requested")
            raise unauthorized("jupyterhub")
        else:
            if resp.status == 403:
                err = web.HTTPInternalServerError(
                    reason="Permission failure verifying user's JupyterHub API token"
                )
            elif resp.status >= 500:
                err = web.HTTPBadGateway(
                    reason="Upstream failure verifying user's JupyterHub API token"
                )
            else:
                err = web.HTTPInternalServerError(
                    reason="Failure verifying user's JupyterHub API token"
                )

            self.log.error(
                "%s - code: %s, reason: %s", err.reason, resp.status, resp.reason
            )
            raise err 
Example #14
Source File: auth.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def raise_auth_error(self, err):
        self.log.error("Kerberos failure: %s", err)
        raise web.HTTPInternalServerError(reason="Error during kerberos authentication") 
Example #15
Source File: api.py    From aiohttp-security with Apache License 2.0 5 votes vote down vote up
def forget(request, response):
    """Forget previously remembered identity.

    Usually it clears cookie or server-side storage to forget user
    session.
    """
    identity_policy = request.config_dict.get(IDENTITY_KEY)
    if identity_policy is None:
        text = ("Security subsystem is not initialized, "
                "call aiohttp_security.setup(...) first")
        # in order to see meaningful exception message both: on console
        # output and rendered page we add same message to *reason* and
        # *text* arguments.
        raise web.HTTPInternalServerError(reason=text, text=text)
    await identity_policy.forget(request, response) 
Example #16
Source File: handlers.py    From schemathesis with MIT License 5 votes vote down vote up
def performance(request: web.Request) -> web.Response:
    # Emulate bad performance on certain input type
    # This endpoint is for Schemathesis targeted testing, the failure should be discovered
    decoded = await request.json()
    number = str(decoded).count("0")
    if number > 0:
        await asyncio.sleep(0.01 * number)
    if number > 10:
        raise web.HTTPInternalServerError
    return web.json_response({"slow": True}) 
Example #17
Source File: mako_example.py    From aiohttp-utils with MIT License 5 votes vote down vote up
def render_mako(request, data):
    handler = request.match_info.handler
    template_name = handler.__dict__.get('template', None)
    if not template_name:
        raise web.HTTPNotAcceptable(text='text/html not supported.')
    if not isinstance(data, Mapping):
        raise web.HTTPInternalServerError(
            text="context should be mapping, not {}".format(type(data)))
    template = request.app['mako_lookup'].get_template(template_name)
    text = template.render_unicode(**data)
    return web.Response(text=text, content_type=request['selected_media_type'])


# ##### Configuration ##### 
Example #18
Source File: app_aiohttp.py    From python-sensor with MIT License 5 votes vote down vote up
def five_hundred(request):
    return web.HTTPInternalServerError(reason="I must simulate errors.", text="Simulated server error.") 
Example #19
Source File: aioserver.py    From python-sensor with MIT License 5 votes vote down vote up
def five_hundred(request):
    return web.HTTPInternalServerError(reason="I must simulate errors.", text="Simulated server error.") 
Example #20
Source File: handlers.py    From schemathesis with MIT License 5 votes vote down vote up
def flaky(request: web.Request) -> web.Response:
    config = request.app["config"]
    if config["should_fail"]:
        config["should_fail"] = False
        raise web.HTTPInternalServerError
    return web.json_response({"result": "flaky!"}) 
Example #21
Source File: handlers.py    From schemathesis with MIT License 5 votes vote down vote up
def multiple_failures(request: web.Request) -> web.Response:
    id_value = int(request.query["id"])
    if id_value == 0:
        raise web.HTTPInternalServerError
    if id_value > 0:
        raise web.HTTPGatewayTimeout
    return web.json_response({"result": "OK"}) 
Example #22
Source File: __init__.py    From aiohttp-mako with Apache License 2.0 5 votes vote down vote up
def render_string(template_name, request, context, *, app_key):
    lookup = request.app.get(app_key)

    if lookup is None:
        raise web.HTTPInternalServerError(
            text=("Template engine is not initialized, "
                  "call aiohttp_mako.setup(app_key={}) first"
                  "".format(app_key)))
    try:
        template = lookup.get_template(template_name)
    except TemplateLookupException as e:
        raise web.HTTPInternalServerError(
            text="Template '{}' not found".format(template_name)) from e
    if not isinstance(context, Mapping):
        raise web.HTTPInternalServerError(
            text="context should be mapping, not {}".format(type(context)))
    if request.get(REQUEST_CONTEXT_KEY):
        context = dict(request[REQUEST_CONTEXT_KEY], **context)
    try:
        text = template.render_unicode(**context)
    except Exception:  # pragma: no cover
        exc_info = sys.exc_info()
        errtext = text_error_template().render(
            error=exc_info[1],
            traceback=exc_info[2])
        exc = MakoRenderingException(errtext).with_traceback(exc_info[2])
        raise exc

    return text 
Example #23
Source File: http.py    From tomodachi with MIT License 5 votes vote down vote up
def get_aiohttp_response(self, context: Dict, default_charset: Optional[str] = None, default_content_type: Optional[str] = None) -> web.Response:
        if self.missing_content_type:
            self.charset = default_charset
            self.content_type = default_content_type

        charset = self.charset
        if hdrs.CONTENT_TYPE in self._headers and ';' in self._headers[hdrs.CONTENT_TYPE]:
            try:
                charset = str([v for v in self._headers[hdrs.CONTENT_TYPE].split(';') if 'charset=' in v][0]).replace('charset=', '').strip()
            except IndexError:
                pass
        elif hdrs.CONTENT_TYPE in self._headers and ';' not in self._headers[hdrs.CONTENT_TYPE]:
            charset = None

        if self._body and not isinstance(self._body, bytes) and charset:
            body = self._body
            try:
                body_value = body.encode(charset.lower())
            except (ValueError, LookupError, UnicodeEncodeError) as e:
                logging.getLogger('exception').exception('Uncaught exception: {}'.format(str(e)))
                raise web.HTTPInternalServerError() from e  # type: ignore
        elif self._body:
            body_value = self._body.encode() if not isinstance(self._body, bytes) else self._body
        else:
            body_value = b''

        response = web.Response(body=body_value,  # type: ignore
                                status=self._status,
                                reason=self._reason,
                                headers=self._headers,
                                content_type=self.content_type,
                                charset=self.charset)   # type: web.Response
        return response 
Example #24
Source File: htmlfile.py    From sockjs with Apache License 2.0 5 votes vote down vote up
def process(self):
        request = self.request

        try:
            callback = request.query.get("c", None)
        except Exception:
            callback = request.GET.get("c", None)

        if callback is None:
            await self.session._remote_closed()
            return web.HTTPInternalServerError(text='"callback" parameter required')

        elif not self.check_callback.match(callback):
            await self.session._remote_closed()
            return web.HTTPInternalServerError(text='invalid "callback" parameter')

        headers = (
            (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"),
            (hdrs.CACHE_CONTROL, CACHE_CONTROL),
            (hdrs.CONNECTION, "close"),
        )
        headers += session_cookie(request)
        headers += cors_headers(request.headers)

        # open sequence (sockjs protocol)
        resp = self.response = web.StreamResponse(headers=headers)
        await resp.prepare(self.request)
        await resp.write(
            b"".join((PRELUDE1, callback.encode("utf-8"), PRELUDE2, b" " * 1024))
        )

        # handle session
        await self.handle_session()

        return resp 
Example #25
Source File: xhrsend.py    From sockjs with Apache License 2.0 5 votes vote down vote up
def process(self):
        request = self.request

        if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS):
            return web.HTTPForbidden(text="Method is not allowed")

        if self.request.method == hdrs.METH_OPTIONS:
            headers = (
                (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),
                (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
            )
            headers += session_cookie(request)
            headers += cors_headers(request.headers)
            headers += cache_headers()
            return web.Response(status=204, headers=headers)

        data = await request.read()
        if not data:
            return web.HTTPInternalServerError(text="Payload expected.")

        try:
            messages = loads(data.decode(ENCODING))
        except Exception:
            return web.HTTPInternalServerError(text="Broken JSON encoding.")

        await self.session._remote_messages(messages)

        headers = (
            (hdrs.CONTENT_TYPE, "text/plain; charset=UTF-8"),
            (hdrs.CACHE_CONTROL, CACHE_CONTROL),
        )
        headers += session_cookie(request)
        headers += cors_headers(request.headers)

        return web.Response(status=204, headers=headers) 
Example #26
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 #27
Source File: __init__.py    From aiohttp-jinja2 with Apache License 2.0 5 votes vote down vote up
def render_string(
    template_name: str,
    request: web.Request,
    context: Dict[str, Any],
    *,
    app_key: str = APP_KEY
) -> str:
    env = request.config_dict.get(app_key)
    if env is None:
        text = ("Template engine is not initialized, "
                "call aiohttp_jinja2.setup(..., app_key={}) first"
                "".format(app_key))
        # in order to see meaningful exception message both: on console
        # output and rendered page we add same message to *reason* and
        # *text* arguments.
        raise web.HTTPInternalServerError(reason=text, text=text)
    try:
        template = env.get_template(template_name)
    except jinja2.TemplateNotFound as e:
        text = "Template '{}' not found".format(template_name)
        raise web.HTTPInternalServerError(reason=text, text=text) from e
    if not isinstance(context, Mapping):
        text = "context should be mapping, not {}".format(type(context))
        # same reason as above
        raise web.HTTPInternalServerError(reason=text, text=text)
    if request.get(REQUEST_CONTEXT_KEY):
        context = dict(request[REQUEST_CONTEXT_KEY], **context)
    text = template.render(context)
    return text 
Example #28
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!")