Exemplo n.º 1
0
    async def stream_callback(self, response: HTTPResponse) -> None:
        """
        Write the response.
        """

        try:
            headers = [(str(name).encode("latin-1"),
                        str(value).encode("latin-1"))
                       for name, value in response.headers.items()]
        except AttributeError:
            logger.error(
                "Invalid response object for url %s, "
                "Expected Type: HTTPResponse, Actual Type: %s",
                self.request.url,
                type(response),
            )
            exception = ServerError("Invalid response type")
            response = self.sanic_app.error_handler.response(
                self.request, exception)
            headers = [(str(name).encode("latin-1"),
                        str(value).encode("latin-1"))
                       for name, value in response.headers.items()
                       if name not in (b"Set-Cookie", )]

        if "content-length" not in response.headers and not isinstance(
                response, StreamingHTTPResponse):
            headers += [(b"content-length",
                         str(len(response.body)).encode("latin-1"))]

        if response.cookies:
            cookies = SimpleCookie()
            cookies.load(response.cookies)
            headers += [(b"set-cookie", cookie.encode("utf-8"))
                        for name, cookie in response.cookies.items()]

        await self.transport.send({
            "type": "http.response.start",
            "status": response.status,
            "headers": headers,
        })

        if isinstance(response, StreamingHTTPResponse):
            response.protocol = self.transport.get_protocol()
            await response.stream()
            await response.protocol.complete()

        else:
            await self.transport.send({
                "type": "http.response.body",
                "body": response.body,
                "more_body": False,
            })
Exemplo n.º 2
0
    async def stream_callback(self, response: HTTPResponse) -> None:
        """
        Write the response.
        """
        headers: List[Tuple[bytes, bytes]] = []
        cookies: Dict[str, str] = {}
        try:
            cookies = {
                v.key: v
                for _, v in list(
                    filter(
                        lambda item: item[0].lower() == "set-cookie",
                        response.headers.items(),
                    )
                )
            }
            headers += [
                (str(name).encode("latin-1"), str(value).encode("latin-1"))
                for name, value in response.headers.items()
                if name.lower() not in ["set-cookie"]
            ]
        except AttributeError:
            logger.error(
                "Invalid response object for url %s, "
                "Expected Type: HTTPResponse, Actual Type: %s",
                self.request.url,
                type(response),
            )
            exception = ServerError("Invalid response type")
            response = self.sanic_app.error_handler.response(
                self.request, exception
            )
            headers = [
                (str(name).encode("latin-1"), str(value).encode("latin-1"))
                for name, value in response.headers.items()
                if name not in (b"Set-Cookie",)
            ]

        if "content-length" not in response.headers and not isinstance(
            response, StreamingHTTPResponse
        ):
            headers += [
                (b"content-length", str(len(response.body)).encode("latin-1"))
            ]

        if "content-type" not in response.headers:
            headers += [
                (b"content-type", str(response.content_type).encode("latin-1"))
            ]

        if response.cookies:
            cookies.update(
                {
                    v.key: v
                    for _, v in response.cookies.items()
                    if v.key not in cookies.keys()
                }
            )

        headers += [
            (b"set-cookie", cookie.encode("utf-8"))
            for k, cookie in cookies.items()
        ]

        await self.transport.send(
            {
                "type": "http.response.start",
                "status": response.status,
                "headers": headers,
            }
        )

        if isinstance(response, StreamingHTTPResponse):
            response.protocol = self.transport.get_protocol()
            await response.stream()
            await response.protocol.complete()

        else:
            await self.transport.send(
                {
                    "type": "http.response.body",
                    "body": response.body,
                    "more_body": False,
                }
            )