Exemplo n.º 1
0
    async def default_response(self, scope, receive, send):
        if scope["type"] == "websocket":
            websocket_close = WebSocketClose()
            await websocket_close(receive, send)
            return

        raise HTTPException(status_code=status_codes.HTTP_404)
Exemplo n.º 2
0
    def not_found(self, scope: Scope) -> ASGIInstance:
        if scope["type"] == "websocket":
            return WebSocketClose()

        # If we're running inside a starlette application then raise an
        # exception, so that the configurable exception handler can deal with
        # returning the response. For plain ASGI apps, just return the response.
        if "app" in scope:
            raise HTTPException(status_code=404)
        return PlainTextResponse("Not Found", status_code=404)
Exemplo n.º 3
0
    async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] == "websocket":
            websocket_close = WebSocketClose()
            await websocket_close(scope, receive, send)
            return

        # If we're running inside a starlette application then raise an
        # exception, so that the configurable exception handler can deal with
        # returning the response. For plain ASGI apps, just return the response.
        if "app" in scope:
            raise HTTPException(status_code=404)
        else:
            response = PlainTextResponse("Not Found", status_code=404)
        await response(scope, receive, send)
Exemplo n.º 4
0
    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        """
        A route may be used in isolation as a stand-alone ASGI app.
        This is a somewhat contrived case, as they'll almost always be used
        within a Router, but could be useful for some tooling and minimal apps.
        """
        match, child_scope = self.matches(scope)
        if match == Match.NONE:
            if scope["type"] == "http":
                response = PlainTextResponse("Not Found", status_code=404)
                await response(scope, receive, send)
            elif scope["type"] == "websocket":
                websocket_close = WebSocketClose()
                await websocket_close(scope, receive, send)
            return

        scope.update(child_scope)
        await self.handle(scope, receive, send)
Exemplo n.º 5
0
    async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
        """
        App without ASGI middleware.
        """
        if scope["type"] == "lifespan":
            return await self.lifespan(scope, receive, send)

        handler: Optional[ASGIApp] = None

        try:
            path_params, handler = self.router.search(scope["type"],
                                                      scope["path"])
            scope["path_params"] = path_params
        except NoMatchFound:
            pass

        if handler is None:
            if scope["type"] == "http":
                raise HTTPException(404)
            handler = WebSocketClose(WS_1001_GOING_AWAY)

        return await handler(scope, receive, send)
Exemplo n.º 6
0
    async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
        """
        App without ASGI middleware.
        """
        if scope["type"] == "lifespan":
            raise NotImplementedError(
                "Maybe you want to use `Index` replace `Application`")

        handler: Optional[ASGIApp] = None

        try:
            path_params, handler = self.router.search(scope["type"],
                                                      scope["path"])
            scope["path_params"] = path_params
        except NoMatchFound:
            pass

        if handler is None:
            if scope["type"] == "http":
                raise HTTPException(404)
            handler = WebSocketClose(WS_1001_GOING_AWAY)

        return await handler(scope, receive, send)
Exemplo n.º 7
0
    async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
        """
        App without ASGI middleware.

        For lifespan, call Index directly.
        For http/websocket, find the appropriate subapp, or Index itself.
        """
        if scope["type"] == "lifespan":
            return await self.lifespan(scope, receive, send)

        path = scope["path"]
        root_path = scope.get("root_path", "")
        has_received = False

        async def subreceive() -> Message:
            nonlocal has_received
            has_received = True
            return await receive()

        async def subsend(message: Message) -> None:
            if message["type"] == "http.response.start" and message[
                    "status"] == 404:
                raise NoMatchFound()
            await send(message)

        # Call into a submounted app, if one exists.
        for path_prefix, app in filter(
                lambda item: path.startswith(item[0] + "/"), self.mount_apps):
            if isinstance(app, WSGIMiddleware) and scope["type"] != "http":
                continue
            subscope = copy.copy(scope)
            subscope["path"] = path[len(path_prefix):]
            subscope["root_path"] = root_path + path_prefix
            try:
                await app(subscope, subreceive, subsend)
                return
            except NoMatchFound:
                if has_received:  # has call received
                    raise HTTPException(404)
            except HTTPException as e:
                if e.status_code != 404 or has_received:
                    raise e

        handler: typing.Optional[ASGIApp] = None

        try:
            path_params, endpoint = self.router.search(scope["type"],
                                                       scope["path"])
            scope["path_params"] = path_params
            request = self.factory_class[scope["type"]](scope, receive,
                                                        send)  # type: ignore
            get_handler = await parse_params(endpoint, request)

            for middleware in getattr(endpoint, "middlewares", ()):
                get_handler = middleware(get_handler)

            if scope["type"] == "http":
                handler = convert(await get_handler(request))
            else:
                handler = get_handler(request)
        except NoMatchFound:
            if scope["type"] == "http" or self.try_html:
                # only html, no middleware/background tasks or other anything
                handler = try_html(self.factory_class["http"](scope, receive,
                                                              send))

        if handler is None:
            if scope["type"] == "http":
                raise HTTPException(404)
            handler = WebSocketClose(WS_1001_GOING_AWAY)

        return await handler(scope, receive, send)