Pure-Python HTTP/2 framing
hyperframe is a pure-Python library providing the HTTP/2 framing code used in the hyper project. It allows for creating, serializing, and parsing HTTP/2 frames from a binary stream. The current version is 6.1.0, and it is actively maintained as part of the python-hyper organization.
Warnings
- breaking In version 6.0.0, the base class for `InvalidPaddingError` and `InvalidFrameError` exceptions changed from `ValueError` to `HyperframeError`. `HyperframeError` was introduced as the new base class for all exceptions in the module.
- gotcha Starting with version 5.0.0, `hyperframe` no longer raises an exception for unknown frame types. Instead, it wraps them in an `ExtensionFrame` object. This means code expecting exceptions for unknown frames will need to handle `ExtensionFrame` instead.
- gotcha The `parse_body` and `parse_frame_header` methods expect `memoryview` objects for performance reasons. Passing raw `bytes` or `bytearray` directly might work in some contexts but is not the intended or most efficient usage.
Install
-
pip install hyperframe
Imports
- Frame
from hyperframe.frame import Frame
- DataFrame
from hyperframe.frame import DataFrame
- HyperframeError
from hyperframe.exceptions import HyperframeError
Quickstart
from hyperframe.frame import DataFrame, Frame
# Create a DATA frame
f = DataFrame(stream_id=5)
f.data = b'some binary data'
f.flags.add('END_STREAM')
f.flags.add('PADDED')
f.padding_length = 30
# Serialize the frame
data = f.serialize()
print(f"Serialized frame: {data.hex()}")
# Parse a frame header from binary data
header_bytes = data[:9] # HTTP/2 frame headers are 9 bytes
parsed_frame_header, length = Frame.parse_frame_header(memoryview(header_bytes))
print(f"Parsed frame type: {type(parsed_frame_header).__name__}, Stream ID: {parsed_frame_header.stream_id}, Length to read: {length}")
# Parse the frame body
body_bytes = data[9:9 + length]
parsed_frame_header.parse_body(memoryview(body_bytes))
print(f"Parsed frame flags: {parsed_frame_header.flags}, Data: {parsed_frame_header.data}")