h2 API

This document details the API of h2.

Semantic Versioning

h2 follows semantic versioning for its public API. Please note that the guarantees of semantic versioning apply only to the API that is documented here. Simply because a method or data field is not prefaced by an underscore does not make it part of h2’s public API. Anything not documented here is subject to change at any time.

Connection

class h2.connection.H2Connection(config=None)[source]

A low-level HTTP/2 connection object. This handles building and receiving frames and maintains both connection and per-stream state for all streams on this connection.

This wraps a HTTP/2 Connection state machine implementation, ensuring that frames can only be sent/received when the connection is in a valid state. It also builds stream state machines on demand to ensure that the constraints of those state machines are met as well. Attempts to create frames that cannot be sent will raise a ProtocolError.

Changed in version 2.3.0: Added the header_encoding keyword argument.

Changed in version 2.5.0: Added the config keyword argument. Deprecated the client_side and header_encoding parameters.

Changed in version 3.0.0: Removed deprecated parameters and properties.

Parameters:config (H2Configuration) –

The configuration for the HTTP/2 connection.

New in version 2.5.0.

acknowledge_received_data(acknowledged_size, stream_id)[source]

Inform the H2Connection that a certain number of flow-controlled bytes have been processed, and that the space should be handed back to the remote peer at an opportune time.

New in version 2.5.0.

Parameters:
  • acknowledged_size (int) – The total flow-controlled size of the data that has been processed. Note that this must include the amount of padding that was sent with that data.
  • stream_id (int) – The ID of the stream on which this data was received.
Returns:

Nothing

Return type:

None

advertise_alternative_service(field_value, origin=None, stream_id=None)[source]

Notify a client about an available Alternative Service.

An Alternative Service is defined in RFC 7838. An Alternative Service notification informs a client that a given origin is also available elsewhere.

Alternative Services can be advertised in two ways. Firstly, they can be advertised explicitly: that is, a server can say “origin X is also available at Y”. To advertise like this, set the origin argument and not the stream_id argument. Alternatively, they can be advertised implicitly: that is, a server can say “the origin you’re contacting on stream X is also available at Y”. To advertise like this, set the stream_id argument and not the origin argument.

The explicit method of advertising can be done as long as the connection is active. The implicit method can only be done after the client has sent the request headers and before the server has sent the response headers: outside of those points, h2 will forbid sending the Alternative Service advertisement by raising a ProtocolError.

The field_value parameter is specified in RFC 7838. h2 does not validate or introspect this argument: the user is required to ensure that it’s well-formed. field_value corresponds to RFC 7838’s “Alternative Service Field Value”.

Note

It is strongly preferred to use the explicit method of advertising Alternative Services. The implicit method of advertising Alternative Services has a number of subtleties and can lead to inconsistencies between the server and client. h2 allows both mechanisms, but caution is strongly advised.

New in version 2.3.0.

Parameters:
  • field_value (bytes) – The RFC 7838 Alternative Service Field Value. This argument is not introspected by h2: the user is responsible for ensuring that it is well-formed.
  • origin (bytes or None) – The origin/authority to which the Alternative Service being advertised applies. Must not be provided at the same time as stream_id.
  • stream_id (int or None) – The ID of the stream which was sent to the authority for which this Alternative Service advertisement applies. Must not be provided at the same time as origin.
Returns:

Nothing.

clear_outbound_data_buffer()[source]

Clears the outbound data buffer, such that if this call was immediately followed by a call to data_to_send, that call would return no data.

This method should not normally be used, but is made available to avoid exposing implementation details.

close_connection(error_code=0, additional_data=None, last_stream_id=None)[source]

Close a connection, emitting a GOAWAY frame.

Changed in version 2.4.0: Added additional_data and last_stream_id arguments.

Parameters:
  • error_code – (optional) The error code to send in the GOAWAY frame.
  • additional_data – (optional) Additional debug data indicating a reason for closing the connection. Must be a bytestring.
  • last_stream_id – (optional) The last stream which was processed by the sender. Defaults to highest_inbound_stream_id.
Returns:

Nothing

config = None

The configuration for this HTTP/2 connection object.

New in version 2.5.0.

data_to_send(amount=None)[source]

Returns some data for sending out of the internal data buffer.

This method is analogous to read on a file-like object, but it doesn’t block. Instead, it returns as much data as the user asks for, or less if that much data is not available. It does not perform any I/O, and so uses a different name.

Parameters:amount (int) – (optional) The maximum amount of data to return. If not set, or set to None, will return as much data as possible.
Returns:A bytestring containing the data to send on the wire.
Return type:bytes
end_stream(stream_id)[source]

Cleanly end a given stream.

This method ends a stream by sending an empty DATA frame on that stream with the END_STREAM flag set.

Parameters:stream_id (int) – The ID of the stream to end.
Returns:Nothing
get_next_available_stream_id()[source]

Returns an integer suitable for use as the stream ID for the next stream created by this endpoint. For server endpoints, this stream ID will be even. For client endpoints, this stream ID will be odd. If no stream IDs are available, raises NoAvailableStreamIDError.

Warning

The return value from this function does not change until the stream ID has actually been used by sending or pushing headers on that stream. For that reason, it should be called as close as possible to the actual use of the stream ID.

New in version 2.0.0.

Raises:NoAvailableStreamIDError
Returns:The next free stream ID this peer can use to initiate a stream.
Return type:int
increment_flow_control_window(increment, stream_id=None)[source]

Increment a flow control window, optionally for a single stream. Allows the remote peer to send more data.

Changed in version 2.0.0: Rejects attempts to increment the flow control window by out of range values with a ValueError.

Parameters:
  • increment (int) – The amount to increment the flow control window by.
  • stream_id (int or None) – (optional) The ID of the stream that should have its flow control window opened. If not present or None, the connection flow control window will be opened instead.
Returns:

Nothing

Raises:

ValueError

initiate_connection()[source]

Provides any data that needs to be sent at the start of the connection. Must be called for both clients and servers.

initiate_upgrade_connection(settings_header=None)[source]

Call to initialise the connection object for use with an upgraded HTTP/2 connection (i.e. a connection negotiated using the Upgrade: h2c HTTP header).

This method differs from initiate_connection in several ways. Firstly, it handles the additional SETTINGS frame that is sent in the HTTP2-Settings header field. When called on a client connection, this method will return a bytestring that the caller can put in the HTTP2-Settings field they send on their initial request. When called on a server connection, the user must provide the value they received from the client in the HTTP2-Settings header field to the settings_header argument, which will be used appropriately.

Additionally, this method sets up stream 1 in a half-closed state appropriate for this side of the connection, to reflect the fact that the request is already complete.

Finally, this method also prepares the appropriate preamble to be sent after the upgrade.

New in version 2.3.0.

Parameters:settings_header (bytes) – (optional, server-only): The value of the HTTP2-Settings header field received from the client.
Returns:For clients, a bytestring to put in the HTTP2-Settings. For servers, returns nothing.
Return type:bytes or None
local_flow_control_window(stream_id)[source]

Returns the maximum amount of data that can be sent on stream stream_id.

This value will never be larger than the total data that can be sent on the connection: even if the given stream allows more data, the connection window provides a logical maximum to the amount of data that can be sent.

The maximum data that can be sent in a single data frame on a stream is either this value, or the maximum frame size, whichever is smaller.

Parameters:stream_id (int) – The ID of the stream whose flow control window is being queried.
Returns:The amount of data in bytes that can be sent on the stream before the flow control window is exhausted.
Return type:int
max_inbound_frame_size = None

The maximum size of a frame that can be received by this peer, in bytes.

max_outbound_frame_size = None

The maximum size of a frame that can be emitted by this peer, in bytes.

open_inbound_streams

The current number of open inbound streams.

open_outbound_streams

The current number of open outbound streams.

ping(opaque_data)[source]

Send a PING frame.

Parameters:opaque_data – A bytestring of length 8 that will be sent in the PING frame.
Returns:Nothing
prioritize(stream_id, weight=None, depends_on=None, exclusive=None)[source]

Notify a server about the priority of a stream.

Stream priorities are a form of guidance to a remote server: they inform the server about how important a given response is, so that the server may allocate its resources (e.g. bandwidth, CPU time, etc.) accordingly. This exists to allow clients to ensure that the most important data arrives earlier, while less important data does not starve out the more important data.

Stream priorities are explained in depth in RFC 7540 Section 5.3.

This method updates the priority information of a single stream. It may be called well before a stream is actively in use, or well after a stream is closed.

Warning

RFC 7540 allows for servers to change the priority of streams. However, h2 does not allow server stacks to do this. This is because most clients do not adequately know how to respond when provided conflicting priority information, and relatively little utility is provided by making that functionality available.

Note

h2 does not maintain any information about the RFC 7540 priority tree. That means that h2 does not prevent incautious users from creating invalid priority trees, particularly by creating priority loops. While some basic error checking is provided by h2, users are strongly recommended to understand their prioritisation strategies before using the priority tools here.

Note

Priority information is strictly advisory. Servers are allowed to disregard it entirely. Avoid relying on the idea that your priority signaling will definitely be obeyed.

New in version 2.4.0.

Parameters:
  • stream_id (int) – The ID of the stream to prioritize.
  • weight (int) – The weight to give the stream. Defaults to 16, the default weight of any stream. May be any value between 1 and 256 inclusive. The relative weight of a stream indicates what proportion of available resources will be allocated to that stream.
  • depends_on (int) – The ID of the stream on which this stream depends. This stream will only be progressed if it is impossible to progress the parent stream (the one on which this one depends). Passing the value 0 means that this stream does not depend on any other. Defaults to 0.
  • exclusive (bool) – Whether this stream is an exclusive dependency of its “parent” stream (i.e. the stream given by depends_on). If a stream is an exclusive dependency of another, that means that all previously-set children of the parent are moved to become children of the new exclusively-dependent stream. Defaults to False.
push_stream(stream_id, promised_stream_id, request_headers)[source]

Push a response to the client by sending a PUSH_PROMISE frame.

If it is important to send HPACK “never indexed” header fields (as defined in RFC 7451 Section 7.1.3), the user may instead provide headers using the HPACK library’s HeaderTuple and NeverIndexedHeaderTuple objects.

Parameters:
  • stream_id (int) – The ID of the stream that this push is a response to.
  • promised_stream_id (int) – The ID of the stream that the pushed response will be sent on.
  • request_headers (An iterable of two tuples of bytestrings or HeaderTuple objects.) – The headers of the request that the pushed response will be responding to.
Returns:

Nothing

receive_data(data)[source]

Pass some received HTTP/2 data to the connection for handling.

Parameters:data (bytes) – The data received from the remote peer on the network.
Returns:A list of events that the remote peer triggered by sending this data.
remote_flow_control_window(stream_id)[source]

Returns the maximum amount of data the remote peer can send on stream stream_id.

This value will never be larger than the total data that can be sent on the connection: even if the given stream allows more data, the connection window provides a logical maximum to the amount of data that can be sent.

The maximum data that can be sent in a single data frame on a stream is either this value, or the maximum frame size, whichever is smaller.

Parameters:stream_id (int) – The ID of the stream whose flow control window is being queried.
Returns:The amount of data in bytes that can be received on the stream before the flow control window is exhausted.
Return type:int
reset_stream(stream_id, error_code=0)[source]

Reset a stream.

This method forcibly closes a stream by sending a RST_STREAM frame for a given stream. This is not a graceful closure. To gracefully end a stream, try the end_stream method.

Parameters:
  • stream_id (int) – The ID of the stream to reset.
  • error_code (int) – (optional) The error code to use to reset the stream. Defaults to ErrorCodes.NO_ERROR.
Returns:

Nothing

send_data(stream_id, data, end_stream=False, pad_length=None)[source]

Send data on a given stream.

This method does no breaking up of data: if the data is larger than the value returned by local_flow_control_window for this stream then a FlowControlError will be raised. If the data is larger than max_outbound_frame_size then a FrameTooLargeError will be raised.

h2 does this to avoid buffering the data internally. If the user has more data to send than h2 will allow, consider breaking it up and buffering it externally.

Parameters:
  • stream_id (int) – The ID of the stream on which to send the data.
  • data (bytes) – The data to send on the stream.
  • end_stream (bool) – (optional) Whether this is the last data to be sent on the stream. Defaults to False.
  • pad_length (int) –

    (optional) Length of the padding to apply to the data frame. Defaults to None for no use of padding. Note that a value of 0 results in padding of length 0 (with the “padding” flag set on the frame).

    New in version 2.6.0.

Returns:

Nothing

send_headers(stream_id, headers, end_stream=False, priority_weight=None, priority_depends_on=None, priority_exclusive=None)[source]

Send headers on a given stream.

This function can be used to send request or response headers: the kind that are sent depends on whether this connection has been opened as a client or server connection, and whether the stream was opened by the remote peer or not.

If this is a client connection, calling send_headers will send the headers as a request. It will also implicitly open the stream being used. If this is a client connection and send_headers has already been called, this will send trailers instead.

If this is a server connection, calling send_headers will send the headers as a response. It is a protocol error for a server to open a stream by sending headers. If this is a server connection and send_headers has already been called, this will send trailers instead.

When acting as a server, you may call send_headers any number of times allowed by the following rules, in this order:

  • zero or more times with (':status', '1XX') (where 1XX is a placeholder for any 100-level status code).
  • once with any other status header.
  • zero or one time for trailers.

That is, you are allowed to send as many informational responses as you like, followed by one complete response and zero or one HTTP trailer blocks.

Clients may send one or two header blocks: one request block, and optionally one trailer block.

If it is important to send HPACK “never indexed” header fields (as defined in RFC 7451 Section 7.1.3), the user may instead provide headers using the HPACK library’s HeaderTuple and NeverIndexedHeaderTuple objects.

This method also allows users to prioritize the stream immediately, by sending priority information on the HEADERS frame directly. To do this, any one of priority_weight, priority_depends_on, or priority_exclusive must be set to a value that is not None. For more information on the priority fields, see prioritize.

Warning

In HTTP/2, it is mandatory that all the HTTP/2 special headers (that is, ones whose header keys begin with :) appear at the start of the header block, before any normal headers.

Changed in version 2.3.0: Added support for using HeaderTuple objects to store headers.

Changed in version 2.4.0: Added the ability to provide priority keyword arguments: priority_weight, priority_depends_on, and priority_exclusive.

Parameters:
  • stream_id (int) – The stream ID to send the headers on. If this stream does not currently exist, it will be created.
  • headers (An iterable of two tuples of bytestrings or HeaderTuple objects.) – The request/response headers to send.
  • end_stream (bool) – Whether this headers frame should end the stream immediately (that is, whether no more data will be sent after this frame). Defaults to False.
  • priority_weight (int or None) – Sets the priority weight of the stream. See prioritize for more about how this field works. Defaults to None, which means that no priority information will be sent.
  • priority_depends_on (bool or None) – Sets which stream this one depends on for priority purposes. See prioritize for more about how this field works. Defaults to None, which means that no priority information will be sent.
  • priority_exclusive – Sets whether this stream exclusively depends on the stream given in priority_depends_on for priority purposes. See prioritize for more about how this field workds. Defaults to None, which means that no priority information will be sent.
Returns:

Nothing

update_settings(new_settings)[source]

Update the local settings. This will prepare and emit the appropriate SETTINGS frame.

Parameters:new_settings – A dictionary of {setting: new value}

Configuration

class h2.config.H2Configuration(client_side=True, header_encoding=None, validate_outbound_headers=True, normalize_outbound_headers=True, split_outbound_cookies=False, validate_inbound_headers=True, normalize_inbound_headers=True, logger=None)[source]

An object that controls the way a single HTTP/2 connection behaves.

This object allows the users to customize behaviour. In particular, it allows users to enable or disable optional features, or to otherwise handle various unusual behaviours.

This object has very little behaviour of its own: it mostly just ensures that configuration is self-consistent.

Parameters:
  • client_side (bool) – Whether this object is to be used on the client side of a connection, or on the server side. Affects the logic used by the state machine, the default settings values, the allowable stream IDs, and several other properties. Defaults to True.
  • header_encoding (str, False, or None) –

    Controls whether the headers emitted by this object in events are transparently decoded to unicode strings, and what encoding is used to do that decoding. This defaults to None, meaning that headers will be returned as bytes. To automatically decode headers (that is, to return them as unicode strings), this can be set to the string name of any encoding, e.g. 'utf-8'.

    Changed in version 3.0.0: Changed default value from 'utf-8' to None

  • validate_outbound_headers (bool) – Controls whether the headers emitted by this object are validated against the rules in RFC 7540. Disabling this setting will cause outbound header validation to be skipped, and allow the object to emit headers that may be illegal according to RFC 7540. Defaults to True.
  • normalize_outbound_headers (bool) – Controls whether the headers emitted by this object are normalized before sending. Disabling this setting will cause outbound header normalization to be skipped, and allow the object to emit headers that may be illegal according to RFC 7540. Defaults to True.
  • split_outbound_cookies (bool) – Controls whether the outbound cookie headers are split before sending or not. According to RFC 7540 - 8.1.2.5 the outbound header cookie headers may be split to improve headers compression. Default is False.
  • validate_inbound_headers (bool) – Controls whether the headers received by this object are validated against the rules in RFC 7540. Disabling this setting will cause inbound header validation to be skipped, and allow the object to receive headers that may be illegal according to RFC 7540. Defaults to True.
  • normalize_inbound_headers (bool) –

    Controls whether the headers received by this object are normalized according to the rules of RFC 7540. Disabling this setting may lead to h2 emitting header blocks that some RFCs forbid, e.g. with multiple cookie fields.

    New in version 3.0.0.

  • logger (logging.Logger) –

    A logger that conforms to the requirements for this module, those being no I/O and no context switches, which is needed in order to run in asynchronous operation.

    New in version 2.6.0.

header_encoding

Controls whether the headers emitted by this object in events are transparently decoded to unicode strings, and what encoding is used to do that decoding. This defaults to None, meaning that headers will be returned as bytes. To automatically decode headers (that is, to return them as unicode strings), this can be set to the string name of any encoding, e.g. 'utf-8'.

Events

class h2.events.RequestReceived[source]

The RequestReceived event is fired whenever request headers are received. This event carries the HTTP headers for the given request and the stream ID of the new stream.

Changed in version 2.3.0: Changed the type of headers to HeaderTuple. This has no effect on current users.

Changed in version 2.4.0: Added stream_ended and priority_updated properties.

headers = None

The request headers.

priority_updated = None

If this request also had associated priority information, the associated PriorityUpdated event will be available here.

New in version 2.4.0.

stream_ended = None

If this request also ended the stream, the associated StreamEnded event will be available here.

New in version 2.4.0.

stream_id = None

The Stream ID for the stream this request was made on.

class h2.events.ResponseReceived[source]

The ResponseReceived event is fired whenever response headers are received. This event carries the HTTP headers for the given response and the stream ID of the new stream.

Changed in version 2.3.0: Changed the type of headers to HeaderTuple. This has no effect on current users.

Changed in version 2.4.0: Added stream_ended and priority_updated properties.

headers = None

The response headers.

priority_updated = None

If this response also had associated priority information, the associated PriorityUpdated event will be available here.

New in version 2.4.0.

stream_ended = None

If this response also ended the stream, the associated StreamEnded event will be available here.

New in version 2.4.0.

stream_id = None

The Stream ID for the stream this response was made on.

class h2.events.TrailersReceived[source]

The TrailersReceived event is fired whenever trailers are received on a stream. Trailers are a set of headers sent after the body of the request/response, and are used to provide information that wasn’t known ahead of time (e.g. content-length). This event carries the HTTP header fields that form the trailers and the stream ID of the stream on which they were received.

Changed in version 2.3.0: Changed the type of headers to HeaderTuple. This has no effect on current users.

Changed in version 2.4.0: Added stream_ended and priority_updated properties.

headers = None

The trailers themselves.

priority_updated = None

If the trailers also set associated priority information, the associated PriorityUpdated event will be available here.

New in version 2.4.0.

stream_ended = None

Trailers always end streams. This property has the associated StreamEnded in it.

New in version 2.4.0.

stream_id = None

The Stream ID for the stream on which these trailers were received.

class h2.events.InformationalResponseReceived[source]

The InformationalResponseReceived event is fired when an informational response (that is, one whose status code is a 1XX code) is received from the remote peer.

The remote peer may send any number of these, from zero upwards. These responses are most commonly sent in response to requests that have the expect: 100-continue header field present. Most users can safely ignore this event unless you are intending to use the expect: 100-continue flow, or are for any reason expecting a different 1XX status code.

New in version 2.2.0.

Changed in version 2.3.0: Changed the type of headers to HeaderTuple. This has no effect on current users.

Changed in version 2.4.0: Added priority_updated property.

headers = None

The headers for this informational response.

priority_updated = None

If this response also had associated priority information, the associated PriorityUpdated event will be available here.

New in version 2.4.0.

stream_id = None

The Stream ID for the stream this informational response was made on.

class h2.events.DataReceived[source]

The DataReceived event is fired whenever data is received on a stream from the remote peer. The event carries the data itself, and the stream ID on which the data was received.

Changed in version 2.4.0: Added stream_ended property.

data = None

The data itself.

flow_controlled_length = None

The amount of data received that counts against the flow control window. Note that padding counts against the flow control window, so when adjusting flow control you should always use this field rather than len(data).

stream_ended = None

If this data chunk also completed the stream, the associated StreamEnded event will be available here.

New in version 2.4.0.

stream_id = None

The Stream ID for the stream this data was received on.

class h2.events.WindowUpdated[source]

The WindowUpdated event is fired whenever a flow control window changes size. HTTP/2 defines flow control windows for connections and streams: this event fires for both connections and streams. The event carries the ID of the stream to which it applies (set to zero if the window update applies to the connection), and the delta in the window size.

delta = None

The window delta.

stream_id = None

The Stream ID of the stream whose flow control window was changed. May be 0 if the connection window was changed.

class h2.events.RemoteSettingsChanged[source]

The RemoteSettingsChanged event is fired whenever the remote peer changes its settings. It contains a complete inventory of changed settings, including their previous values.

In HTTP/2, settings changes need to be acknowledged. h2 automatically acknowledges settings changes for efficiency. However, it is possible that the caller may not be happy with the changed setting.

When this event is received, the caller should confirm that the new settings are acceptable. If they are not acceptable, the user should close the connection with the error code PROTOCOL_ERROR.

Changed in version 2.0.0: Prior to this version the user needed to acknowledge settings changes. This is no longer the case: h2 now automatically acknowledges them.

changed_settings = None

A dictionary of setting byte to ChangedSetting, representing the changed settings.

classmethod from_settings(old_settings, new_settings)[source]

Build a RemoteSettingsChanged event from a set of changed settings.

Parameters:
  • old_settings – A complete collection of old settings, in the form of a dictionary of {setting: value}.
  • new_settings – All the changed settings and their new values, in the form of a dictionary of {setting: value}.
class h2.events.PingReceived[source]

The PingReceived event is fired whenever a PING is received. It contains the ‘opaque data’ of the PING frame. A ping acknowledgment with the same ‘opaque data’ is automatically emitted after receiving a ping.

New in version 3.1.0.

ping_data = None

The data included on the ping.

class h2.events.PingAckReceived[source]

The PingAckReceived event is fired whenever a PING acknowledgment is received. It contains the ‘opaque data’ of the PING+ACK frame, allowing the user to correlate PINGs and calculate RTT.

New in version 3.1.0.

Changed in version 4.0.0: Removed deprecated but equivalent PingAcknowledged.

ping_data = None

The data included on the ping.

class h2.events.StreamEnded[source]

The StreamEnded event is fired whenever a stream is ended by a remote party. The stream may not be fully closed if it has not been closed locally, but no further data or headers should be expected on that stream.

stream_id = None

The Stream ID of the stream that was closed.

class h2.events.StreamReset[source]

The StreamReset event is fired in two situations. The first is when the remote party forcefully resets the stream. The second is when the remote party has made a protocol error which only affects a single stream. In this case, h2 will terminate the stream early and return this event.

Changed in version 2.0.0: This event is now fired when h2 automatically resets a stream.

error_code = None

The error code given. Either one of ErrorCodes or int

remote_reset = None

Whether the remote peer sent a RST_STREAM or we did.

stream_id = None

The Stream ID of the stream that was reset.

class h2.events.PushedStreamReceived[source]

The PushedStreamReceived event is fired whenever a pushed stream has been received from a remote peer. The event carries on it the new stream ID, the ID of the parent stream, and the request headers pushed by the remote peer.

headers = None

The request headers, sent by the remote party in the push.

parent_stream_id = None

The Stream ID of the stream that the push is related to.

pushed_stream_id = None

The Stream ID of the stream created by the push.

class h2.events.SettingsAcknowledged[source]

The SettingsAcknowledged event is fired whenever a settings ACK is received from the remote peer. The event carries on it the settings that were acknowedged, in the same format as h2.events.RemoteSettingsChanged.

changed_settings = None

A dictionary of setting byte to ChangedSetting, representing the changed settings.

class h2.events.PriorityUpdated[source]

The PriorityUpdated event is fired whenever a stream sends updated priority information. This can occur when the stream is opened, or at any time during the stream lifetime.

This event is purely advisory, and does not need to be acted on.

New in version 2.0.0.

depends_on = None

The stream ID this stream now depends on. May be 0.

exclusive = None

Whether the stream exclusively depends on the parent stream. If it does, this stream should inherit the current children of its new parent.

stream_id = None

The ID of the stream whose priority information is being updated.

weight = None

The new stream weight. May be the same as the original stream weight. An integer between 1 and 256.

class h2.events.ConnectionTerminated[source]

The ConnectionTerminated event is fired when a connection is torn down by the remote peer using a GOAWAY frame. Once received, no further action may be taken on the connection: a new connection must be established.

additional_data = None

Additional debug data that can be appended to GOAWAY frame.

error_code = None

The error code cited when tearing down the connection. Should be one of ErrorCodes, but may not be if unknown HTTP/2 extensions are being used.

last_stream_id = None

The stream ID of the last stream the remote peer saw. This can provide an indication of what data, if any, never reached the remote peer and so can safely be resent.

class h2.events.AlternativeServiceAvailable[source]

The AlternativeServiceAvailable event is fired when the remote peer advertises an RFC 7838 Alternative Service using an ALTSVC frame.

This event always carries the origin to which the ALTSVC information applies. That origin is either supplied by the server directly, or inferred by h2 from the :authority pseudo-header field that was sent by the user when initiating a given stream.

This event also carries what RFC 7838 calls the “Alternative Service Field Value”, which is formatted like a HTTP header field and contains the relevant alternative service information. h2 does not parse or in any way modify that information: the user is required to do that.

This event can only be fired on the client end of a connection.

New in version 2.3.0.

field_value = None

The ALTSVC field value. This contains information about the HTTP alternative service being advertised by the server. h2 does not parse this field: it is left exactly as sent by the server. The structure of the data in this field is given by RFC 7838 Section 3.

origin = None

The origin to which the alternative service field value applies. This field is either supplied by the server directly, or inferred by h2 from the :authority pseudo-header field that was sent by the user when initiating the stream on which the frame was received.

class h2.events.UnknownFrameReceived[source]

The UnknownFrameReceived event is fired when the remote peer sends a frame that h2 does not understand. This occurs primarily when the remote peer is employing HTTP/2 extensions that h2 doesn’t know anything about.

RFC 7540 requires that HTTP/2 implementations ignore these frames. h2 does so. However, this event is fired to allow implementations to perform special processing on those frames if needed (e.g. if the implementation is capable of handling the frame itself).

New in version 2.7.0.

frame = None

The hyperframe Frame object that encapsulates the received frame.

Exceptions

class h2.exceptions.H2Error[source]

The base class for all exceptions for the HTTP/2 module.

class h2.exceptions.NoSuchStreamError(stream_id)[source]

Bases: h2.exceptions.ProtocolError

A stream-specific action referenced a stream that does not exist.

Changed in version 2.0.0: Became a subclass of ProtocolError

stream_id = None

The stream ID corresponds to the non-existent stream.

class h2.exceptions.StreamClosedError(stream_id)[source]

Bases: h2.exceptions.NoSuchStreamError

A more specific form of NoSuchStreamError. Indicates that the stream has since been closed, and that all state relating to that stream has been removed.

stream_id = None

The stream ID corresponds to the nonexistent stream.

class h2.exceptions.RFC1122Error[source]

Bases: h2.exceptions.H2Error

Emitted when users attempt to do something that is literally allowed by the relevant RFC, but is sufficiently ill-defined that it’s unwise to allow users to actually do it.

While there is some disagreement about whether or not we should be liberal in what accept, it is a truth universally acknowledged that we should be conservative in what emit.

New in version 2.4.0.

Protocol Errors

class h2.exceptions.ProtocolError[source]

Bases: h2.exceptions.H2Error

An action was attempted in violation of the HTTP/2 protocol.

error_code = 1

The error code corresponds to this kind of Protocol Error.

class h2.exceptions.FrameTooLargeError[source]

Bases: h2.exceptions.ProtocolError

The frame that we tried to send or that we received was too large.

error_code = 6

The error code corresponds to this kind of Protocol Error.

class h2.exceptions.FrameDataMissingError[source]

Bases: h2.exceptions.ProtocolError

The frame that we received is missing some data.

New in version 2.0.0.

error_code = 6

The error code corresponds to this kind of Protocol Error.

class h2.exceptions.TooManyStreamsError[source]

Bases: h2.exceptions.ProtocolError

An attempt was made to open a stream that would lead to too many concurrent streams.

class h2.exceptions.FlowControlError[source]

Bases: h2.exceptions.ProtocolError

An attempted action violates flow control constraints.

error_code = 3

The error code corresponds to this kind of Protocol Error.

class h2.exceptions.StreamIDTooLowError(stream_id, max_stream_id)[source]

Bases: h2.exceptions.ProtocolError

An attempt was made to open a stream that had an ID that is lower than the highest ID we have seen on this connection.

max_stream_id = None

The current highest-seen stream ID.

stream_id = None

The ID of the stream that we attempted to open.

class h2.exceptions.InvalidSettingsValueError(msg, error_code)[source]

An attempt was made to set an invalid Settings value.

New in version 2.0.0.

class h2.exceptions.NoAvailableStreamIDError[source]

Bases: h2.exceptions.ProtocolError

There are no available stream IDs left to the connection. All stream IDs have been exhausted.

New in version 2.0.0.

class h2.exceptions.InvalidBodyLengthError(expected, actual)[source]

Bases: h2.exceptions.ProtocolError

The remote peer sent more or less data that the Content-Length header indicated.

New in version 2.0.0.

class h2.exceptions.UnsupportedFrameError[source]

The remote peer sent a frame that is unsupported in this context.

New in version 2.1.0.

Changed in version 4.0.0: Removed deprecated KeyError parent class.

class h2.exceptions.DenialOfServiceError[source]

Bases: h2.exceptions.ProtocolError

Emitted when the remote peer exhibits a behaviour that is likely to be an attempt to perform a Denial of Service attack on the implementation. This is a form of ProtocolError that carries a different error code, and allows more easy detection of this kind of behaviour.

New in version 2.5.0.

error_code = 11

The error code corresponds to this kind of ProtocolError

HTTP/2 Error Codes

h2/errors

Global error code registry containing the established HTTP/2 error codes.

The current registry is available at: https://tools.ietf.org/html/rfc7540#section-11.4

class h2.errors.ErrorCodes[source]

All known HTTP/2 error codes.

New in version 2.5.0.

CANCEL = 8

Stream cancelled.

COMPRESSION_ERROR = 9

Compression state not updated.

CONNECT_ERROR = 10

TCP connection error for CONNECT method.

ENHANCE_YOUR_CALM = 11

Processing capacity exceeded.

FLOW_CONTROL_ERROR = 3

Flow-control limits exceeded.

FRAME_SIZE_ERROR = 6

Frame size incorrect.

HTTP_1_1_REQUIRED = 13

Use HTTP/1.1 for the request.

INADEQUATE_SECURITY = 12

Negotiated TLS parameters not acceptable.

INTERNAL_ERROR = 2

Implementation fault.

NO_ERROR = 0

Graceful shutdown.

PROTOCOL_ERROR = 1

Protocol error detected.

REFUSED_STREAM = 7

Stream not processed.

SETTINGS_TIMEOUT = 4

Settings not acknowledged.

STREAM_CLOSED = 5

Frame received for closed stream.

Settings

class h2.settings.SettingCodes[source]

All known HTTP/2 setting codes.

New in version 2.6.0.

ENABLE_CONNECT_PROTOCOL = 8

This setting can be used to enable the connect protocol. To enable on a client set this to 1.

ENABLE_PUSH = 2

This setting can be used to disable server push. To disable server push on a client, set this to 0.

HEADER_TABLE_SIZE = 1

Allows the sender to inform the remote endpoint of the maximum size of the header compression table used to decode header blocks, in octets.

INITIAL_WINDOW_SIZE = 4

Indicates the sender’s initial window size (in octets) for stream-level flow control.

MAX_CONCURRENT_STREAMS = 3

Indicates the maximum number of concurrent streams that the sender will allow.

MAX_FRAME_SIZE = 5

Indicates the size of the largest frame payload that the sender is willing to receive, in octets.

MAX_HEADER_LIST_SIZE = 6

This advisory setting informs a peer of the maximum size of header list that the sender is prepared to accept, in octets. The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field.

class h2.settings.Settings(client=True, initial_values=None)[source]

An object that encapsulates HTTP/2 settings state.

HTTP/2 Settings are a complex beast. Each party, remote and local, has its own settings and a view of the other party’s settings. When a settings frame is emitted by a peer it cannot assume that the new settings values are in place until the remote peer acknowledges the setting. In principle, multiple settings changes can be “in flight” at the same time, all with different values.

This object encapsulates this mess. It provides a dict-like interface to settings, which return the current values of the settings in question. Additionally, it keeps track of the stack of proposed values: each time an acknowledgement is sent/received, it updates the current values with the stack of proposed values. On top of all that, it validates the values to make sure they’re allowed, and raises InvalidSettingsValueError if they are not.

Finally, this object understands what the default values of the HTTP/2 settings are, and sets those defaults appropriately.

Changed in version 2.2.0: Added the initial_values parameter.

Changed in version 2.5.0: Added the max_header_list_size property.

Parameters:
  • client (bool) – (optional) Whether these settings should be defaulted for a client implementation or a server implementation. Defaults to True.
  • initial_values – (optional) Any initial values the user would like set, rather than RFC 7540’s defaults.
acknowledge()[source]

The settings have been acknowledged, either by the user (remote settings) or by the remote peer (local settings).

Returns:A dict of {setting: ChangedSetting} that were applied.
clear() → None. Remove all items from D.
enable_connect_protocol

The current value of the ENABLE_CONNECT_PROTOCOL setting.

enable_push

The current value of the ENABLE_PUSH setting.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
header_table_size

The current value of the HEADER_TABLE_SIZE setting.

initial_window_size

The current value of the INITIAL_WINDOW_SIZE setting.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
max_concurrent_streams

The current value of the MAX_CONCURRENT_STREAMS setting.

max_frame_size

The current value of the MAX_FRAME_SIZE setting.

max_header_list_size

The current value of the MAX_HEADER_LIST_SIZE setting. If not set, returns None, which means unlimited.

New in version 2.5.0.

pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → an object providing a view on D's values
class h2.settings.ChangedSetting(setting, original_value, new_value)[source]
new_value = None

The new value after being changed.

original_value = None

The original value before being changed.

setting = None

The setting code given. Either one of SettingCodes or int

Changed in version 2.6.0.