Introduction to h11
The h11 library is a lightweight, pure-Python, and low-level HTTP/1.1 protocol library designed to be used as a building block for other libraries and frameworks. It is useful for anyone needing to interact with HTTP/1.1 without the overhead of more comprehensive libraries like Requests or urllib.
Key Features of h11
- Lightweight and minimal
- Low-level control over HTTP/1.1 communication
- Written in Python
APIs and Code Snippets
h11 offers several useful APIs. Here’s a brief overview of some of the most important ones, along with code examples.
Connection
The h11.Connection
class manages the state of an HTTP/1.1 connection, including sending and receiving data. It operates in one of four states: ‘IDLE’, ‘SEND’, ‘RECV’, or ‘DONE’.
import h11 conn = h11.Connection(h11.CLIENT) print(conn.states)
Request and Response
To send a request and receive a response, you use the h11.Request
and h11.Response
message classes, respectively.
import h11 conn = h11.Connection(h11.CLIENT) request = h11.Request( method='GET', target='/', headers=[('Host', 'example.com'), ('User-Agent', 'h11-example')] ) conn.send(request)
import h11 conn = h11.Connection(h11.SERVER) response = h11.Response( status_code=200, headers=[('Content-Type', 'text/plain')], reason=b'OK' ) conn.send(response)
Data
The h11.Data
class is used to send and receive the actual data payload. Here’s an example:
import h11 conn = h11.Connection(h11.CLIENT) data = h11.Data(data=b'Hello World') conn.send(data)
Event Handling
Handling incoming events is straightforward. Here is an example of handling different types of incoming events:
import h11 conn = h11.Connection(h11.SERVER) request = conn.next_event() if isinstance(request, h11.Request): print('Received request:', request) elif isinstance(request, h11.EndOfMessage): print('End of message')
Example Application
Below is a small example of an HTTP client built using h11:
import h11 import socket host = 'example.com' port = 80 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) conn = h11.Connection(h11.CLIENT) request = h11.Request( method='GET', target='/', headers=[('Host', host), ('User-Agent', 'h11-example')] ) sock.send(conn.send(request)) sock.send(conn.send(h11.EndOfMessage())) while True: event = conn.next_event() if isinstance(event, h11.Response): print('Received response:', event.status_code) elif isinstance(event, h11.Data): print('Received data:', event.data.decode('utf-8')) elif isinstance(event, h11.EndOfMessage): break
This example demonstrates how to create a simple HTTP client that sends a GET request and processes the response using the h11 library.
Hash: 973b98d4ef3aac8c991d5d027837c3c6767ec05ebe20e5c49c03d8dde588de88