How to use the h11.Response function in h11

To help you get started, we’ve selected a few h11 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pgjones / hypercorn / tests / asyncio / test_wsproto.py View on Github external
async def test_bad_framework_http(path: str, event_loop: asyncio.AbstractEventLoop) -> None:
    connection = MockHTTPConnection(path, event_loop, framework=bad_framework)
    await asyncio.sleep(0)  # Yield to allow the server to process
    await connection.transport.closed.wait()
    response, *_ = connection.get_events()
    assert isinstance(response, h11.Response)
    assert response.status_code == 500
github python-hyper / wsproto / test / test_client.py View on Github external
def _make_handshake_rejection(
    status_code: int, body: Optional[bytes] = None
) -> List[Event]:
    client = WSConnection(CLIENT)
    server = h11.Connection(h11.SERVER)
    server.receive_data(client.send(Request(host="localhost", target="/")))
    headers = []
    if body is not None:
        headers.append(("Content-Length", str(len(body))))
    client.receive_data(
        server.send(h11.Response(status_code=status_code, headers=headers))
    )
    if body is not None:
        client.receive_data(server.send(h11.Data(data=body)))
    client.receive_data(server.send(h11.EndOfMessage()))

    return list(client.events())
github encode / uvicorn / uvicorn / protocols / http / h11_impl.py View on Github external
headers = self.default_headers + message.get("headers", [])

            if self.access_log:
                self.access_logger.info(
                    '%s - "%s %s HTTP/%s" %d',
                    get_client_addr(self.scope),
                    self.scope["method"],
                    get_path_with_query_string(self.scope),
                    self.scope["http_version"],
                    status_code,
                    extra={"status_code": status_code, "scope": self.scope},
                )

            # Write response status line and headers
            reason = STATUS_PHRASES[status_code]
            event = h11.Response(
                status_code=status_code, headers=headers, reason=reason
            )
            output = self.conn.send(event)
            self.transport.write(output)

        elif not self.response_complete:
            # Sending response body
            if message_type != "http.response.body":
                msg = "Expected ASGI message 'http.response.body', but got '%s'."
                raise RuntimeError(msg % message_type)

            body = message.get("body", b"")
            more_body = message.get("more_body", False)

            # Write response body
            if self.scope["method"] == "HEAD":
github pgjones / quart / quart / serving.py View on Github external
def _handle_error(self) -> None:
        self._send(h11.Response(status_code=400, headers=[]))
        self._send(h11.EndOfMessage())
github vfaronov / turq / turq / mock.py View on Github external
def _send_fatal_error(self, exc):
        status_code = getattr(exc, 'error_status_hint', 500)
        self._logger.debug('sending error response, status %d', status_code)
        try:
            self.send_event(h11.Response(
                status_code=status_code,
                reason=turq.util.http.default_reason(status_code).encode(),
                headers=[
                    (b'Date', turq.util.http.date().encode()),
                    (b'Content-Type', b'text/plain'),
                    (b'Connection', b'close'),
                ],
            ))
            self.send_event(h11.Data(data=('Error: %s\r\n' % exc).encode()))
            self.send_event(h11.EndOfMessage())
        except Exception as e:
            self._logger.debug('cannot send error response: %s', e)

        # A crude way to avoid the TCP reset problem (RFC 7230 Section 6.6).
        try:
            self._socket.shutdown(socket.SHUT_WR)
github encode / uvicorn / uvicorn / protocols / http / h11_impl.py View on Github external
def handle_upgrade(self, event):
        upgrade_value = None
        for name, value in self.headers:
            if name == b"upgrade":
                upgrade_value = value.lower()

        if upgrade_value != b"websocket" or self.ws_protocol_class is None:
            msg = "Unsupported upgrade request."
            self.logger.warning(msg)
            reason = STATUS_PHRASES[400]
            headers = [
                (b"content-type", b"text/plain; charset=utf-8"),
                (b"connection", b"close"),
            ]
            event = h11.Response(status_code=400, headers=headers, reason=reason)
            output = self.conn.send(event)
            self.transport.write(output)
            event = h11.Data(data=b"Unsupported upgrade request.")
            output = self.conn.send(event)
            self.transport.write(output)
            event = h11.EndOfMessage()
            output = self.conn.send(event)
            self.transport.write(output)
            self.transport.close()
            return

        self.connections.discard(self)
        output = [event.method, b" ", event.target, b" HTTP/1.1\r\n"]
        for name, value in self.headers:
            output += [name, b": ", value, b"\r\n"]
        output.append(b"\r\n")
github python-hyper / wsproto / src / wsproto / handshake.py View on Github external
def _reject(self, event: RejectConnection) -> bytes:
        if self.state != ConnectionState.CONNECTING:
            raise LocalProtocolError(
                "Connection cannot be rejected in state %s" % self.state
            )

        headers = event.headers
        if not event.has_body:
            headers.append((b"content-length", b"0"))
        response = h11.Response(status_code=event.status_code, headers=headers)
        data = self._h11_connection.send(response)
        self._state = ConnectionState.REJECTING
        if not event.has_body:
            data += self._h11_connection.send(h11.EndOfMessage())
            self._state = ConnectionState.CLOSED
        return data
github JeffBelgum / curious / curious / response.py View on Github external
async def respond(status_code, content_type, body):
    log.info(f"Sending {status_code} response with {len(body)} bytes")
    headers = _request_local.transport.basic_headers()
    headers.append(("Content-Type", content_type))
    headers.append(("Content-Length", str(len(body))))
    res = h11.Response(status_code=status_code, headers=headers)
    await _request_local.transport.send(res)
    await _request_local.transport.send(h11.Data(data=body))
    await _request_local.transport.send(h11.EndOfMessage())
github pgjones / quart / quart / serving / websocket.py View on Github external
async def _handle_websocket(self, websocket: Websocket) -> None:
        response = await self.app.handle_websocket(websocket)
        if response is not None:
            if self.active:
                self.connection.close(wsproto.connection.CloseReason.INTERNAL_ERROR)
                self.write(self.connection.bytes_to_send())
            else:
                headers = chain(
                    ((key, value) for key, value in response.headers.items()),
                    self.response_headers(),
                )
                self.write(
                    self.connection._upgrade_connection.send(
                        h11.Response(status_code=response.status_code, headers=headers),
                    ),
                )
                if not suppress_body('GET', response.status_code):
                    async for data in response.response:
                        self.write(
                            self.connection._upgrade_connection.send(h11.Data(data=data)),
                        )
                        await self.drain()
                self.write(
                    self.connection._upgrade_connection.send(h11.EndOfMessage()),
                )
        self.close()