HPACK Header Encoding
hpack is a pure-Python library implementing the HPACK (Header Compression for HTTP/2) algorithm, adhering strictly to RFC 7541. It provides `Encoder` and `Decoder` classes for compressing and decompressing HTTP/2 headers efficiently. Maintained by the python-hyper project, it is currently at version 4.1.0 and sees releases periodically, with major versions several years apart, indicating stable and active maintenance.
Warnings
- breaking In version 3.0.0, the explicit support for the `nghttp2` C-based backend was temporarily removed due to being non-functional. While later versions have re-integrated transparent `nghttp2` usage, this change was breaking for applications directly relying on `nghttp2` integration in 3.0.0.
- breaking Starting with version 3.0.0, the `Encoder` strictly enforces the maximum allowed header table size. Attempts to exceed this limit via dynamic table size updates will now raise `InvalidTableSizeError`.
- gotcha Versions of `hpack` prior to 2.3.0 were vulnerable to the 'HPACK Bomb' denial-of-service attack (CVE-2016-6581), where a small compressed header block could decompress into a disproportionately large amount of memory. Version 2.3.0 introduced `Decoder.max_header_list_size` to mitigate this.
- gotcha In versions 2.1.0 and 2.3.0, several generic exceptions (`IndexError`, `UnicodeDecodeError`) raised during decoding were replaced with more specific `HPACKDecodingError` and `InvalidTableIndex`. Code catching the older, broader exceptions might no longer correctly handle specific HPACK-related failures.
- gotcha As of version 2.2.0, the `Decoder.decode()` method returns `HeaderTuple` or `NeverIndexedHeaderTuple` objects instead of plain tuples. While these behave largely like 2-tuples, code performing strict type-checking (e.g., `isinstance(header, tuple)`) might be affected.
Install
-
pip install hpack
Imports
- Encoder
from hpack import Encoder
- Decoder
from hpack import Decoder
Quickstart
from hpack import Encoder, Decoder
# Example headers
headers = [
(':method', 'GET'),
(':path', '/resource'),
('user-agent', 'hpack-client/1.0'),
('accept-encoding', 'gzip, deflate, br')
]
# Encode headers
encoder = Encoder()
encoded_bytes = encoder.encode(headers)
print(f"Encoded bytes: {encoded_bytes.hex()}")
# Decode headers
decoder = Decoder()
decoded_headers = decoder.decode(encoded_bytes)
print(f"Decoded headers: {decoded_headers}")