API documentation¶
Contents
- API documentation
- Events
- The state machine
- Special constants
- The Connection object
- Error handling
- Message body framing:
Content-Length
and all that - Re-using a connection: keep-alive and pipelining
- Flow control
- Closing connections
- Switching protocols
- Support for
sendfile()
- Identifying h11 in requests and responses
- Chunked Transfer Encoding Delimiters
h11 has a fairly small public API, with all public symbols available directly at the top level:
In [1]: import h11
In [2]: h11.<TAB>
h11.CLIENT h11.MUST_CLOSE
h11.CLOSED h11.NEED_DATA
h11.Connection h11.PAUSED
h11.ConnectionClosed h11.PRODUCT_ID
h11.Data h11.ProtocolError
h11.DONE h11.RemoteProtocolError
h11.EndOfMessage h11.Request
h11.ERROR h11.Response
h11.IDLE h11.SEND_BODY
h11.InformationalResponse h11.SEND_RESPONSE
h11.LocalProtocolError h11.SERVER
h11.MIGHT_SWITCH_PROTOCOL h11.SWITCHED_PROTOCOL
These symbols fall into three main categories: event classes, special
constants used to track different connection states, and the
Connection
class itself. We’ll describe them in that order.
Events¶
Events are the core of h11: the whole point of h11 is to let you think about HTTP transactions as being a series of events sent back and forth between a client and a server, instead of thinking in terms of bytes.
All events behave in essentially similar ways. Let’s take
Request
as an example. Like all events, this is a “final”
class – you cannot subclass it. And like all events, it has several
fields. For Request
, there are four of them:
method
, target
,
headers
, and
http_version
. http_version
defaults to b"1.1"
; the rest have no default, so to create a
Request
you have to specify their values:
In [3]: req = h11.Request(method="GET",
...: target="/",
...: headers=[("Host", "example.com")])
...:
Event constructors accept only keyword arguments, not positional arguments.
Events have a useful repr:
In [4]: req
Out[4]: Request(method=b'GET', target=b'/', headers=[(b'host', b'example.com')], http_version=b'1.1')
And their fields are available as regular attributes:
In [5]: req.method
Out[5]: b'GET'
In [6]: req.target