Skip to content
Myr

extensions.md

This file

Path

docs/advanced/extensions.md

242 lines · 9.2 KiB · Markdown

Last changed by

Docs: fix small typos in Extensions doc (#3138)Michiel W. Beijenbefore adoption4b85e6c

History of this file

Take it

Extensions docs (#3080)Tom Christiebefore adoptionc51af4b

lines 1–4why, one step back
1# Extensions
23Request and response extensions provide a untyped space where additional information may be added.4

Docs: fix small typos in Extensions doc (#3138)Michiel W. Beijenbefore adoption4b85e6c

line 5why, one step back
5Extensions should be used for features that may not be available on all transports, and that do not fit neatly into [the simplified request/response model](https://www.encode.io/httpcore/extensions/) that the underlying `httpcore` package uses as its API.

Extensions docs (#3080)Tom Christiebefore adoptionc51af4b

lines 6–140why, one step back
6
7Several extensions are supported on the request:89```python10# Request timeouts actually implemented as an extension on11# the request, ensuring that they are passed throughout the12# entire call stack.13client = httpx.Client()14response = client.get(15 "https://www.example.com",16 extensions={"timeout": {"connect": 5.0}}17)18response.request.extensions["timeout"]19{"connect": 5.0}20```2122And on the response:2324```python25client = httpx.Client()26response = client.get("https://www.example.com")27print(response.extensions["http_version"]) # b"HTTP/1.1"28# Other server responses could have been29# b"HTTP/0.9", b"HTTP/1.0", or b"HTTP/1.1"30```3132## Request Extensions3334### `"trace"`3536The trace extension allows a callback handler to be installed to monitor the internal37flow of events within the underlying `httpcore` transport.3839The simplest way to explain this is with an example:4041```python42import httpx4344def log(event_name, info):45 print(event_name, info)4647client = httpx.Client()48response = client.get("https://www.example.com/", extensions={"trace": log})49# connection.connect_tcp.started {'host': 'www.example.com', 'port': 443, 'local_address': None, 'timeout': None}50# connection.connect_tcp.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f94d0>}51# connection.start_tls.started {'ssl_context': <ssl.SSLContext object at 0x1093ee750>, 'server_hostname': b'www.example.com', 'timeout': None}52# connection.start_tls.complete {'return_value': <httpcore.backends.sync.SyncStream object at 0x1093f9450>}53# http11.send_request_headers.started {'request': <Request [b'GET']>}54# http11.send_request_headers.complete {'return_value': None}55# http11.send_request_body.started {'request': <Request [b'GET']>}56# http11.send_request_body.complete {'return_value': None}57# http11.receive_response_headers.started {'request': <Request [b'GET']>}58# http11.receive_response_headers.complete {'return_value': (b'HTTP/1.1', 200, b'OK', [(b'Age', b'553715'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 21 Oct 2021 17:08:42 GMT'), (b'Etag', b'"3147526947+ident"'), (b'Expires', b'Thu, 28 Oct 2021 17:08:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1DCD)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'1256')])}59# http11.receive_response_body.started {'request': <Request [b'GET']>}60# http11.receive_response_body.complete {'return_value': None}61# http11.response_closed.started {}62# http11.response_closed.complete {'return_value': None}63```6465The `event_name` and `info` arguments here will be one of the following:6667* `{event_type}.{event_name}.started`, `<dictionary of keyword arguments>`68* `{event_type}.{event_name}.complete`, `{"return_value": <...>}`69* `{event_type}.{event_name}.failed`, `{"exception": <...>}`7071Note that when using async code the handler function passed to `"trace"` must be an `async def ...` function.7273The following event types are currently exposed...7475**Establishing the connection**7677* `"connection.connect_tcp"`78* `"connection.connect_unix_socket"`79* `"connection.start_tls"`8081**HTTP/1.1 events**8283* `"http11.send_request_headers"`84* `"http11.send_request_body"`85* `"http11.receive_response"`86* `"http11.receive_response_body"`87* `"http11.response_closed"`8889**HTTP/2 events**9091* `"http2.send_connection_init"`92* `"http2.send_request_headers"`93* `"http2.send_request_body"`94* `"http2.receive_response_headers"`95* `"http2.receive_response_body"`96* `"http2.response_closed"`9798The exact set of trace events may be subject to change across different versions of `httpcore`. If you need to rely on a particular set of events it is recommended that you pin installation of the package to a fixed version.99100### `"sni_hostname"`101102The server's hostname, which is used to confirm the hostname supplied by the SSL certificate.103104If you want to connect to an explicit IP address rather than using the standard DNS hostname lookup, then you'll need to use this request extension.105106For example:107108``` python109# Connect to '185.199.108.153' but use 'www.encode.io' in the Host header,110# and use 'www.encode.io' when SSL verifying the server hostname.111client = httpx.Client()112headers = {"Host": "www.encode.io"}113extensions = {"sni_hostname": "www.encode.io"}114response = client.get(115 "https://185.199.108.153/path",116 headers=headers,117 extensions=extensions118)119```120121### `"timeout"`122123A dictionary of `str: Optional[float]` timeout values.124125May include values for `'connect'`, `'read'`, `'write'`, or `'pool'`.126127For example:128129```python130# Timeout if a connection takes more than 5 seconds to established, or if131# we are blocked waiting on the connection pool for more than 10 seconds.132client = httpx.Client()133response = client.get(134 "https://www.example.com",135 extensions={"timeout": {"connect": 5.0, "pool": 10.0}}136)137```138139This extension is how the `httpx` timeouts are implemented, ensuring that the timeout values are associated with the request instance and passed throughout the stack. You shouldn't typically be working with this extension directly, but use the higher level `timeout` API instead.140

Document 'target' extension (#3160)Tom Christiebefore adoption45bb65b

lines 141–181why, one step back
141### `"target"`
142143The target that is used as [the HTTP target instead of the URL path](https://datatracker.ietf.org/doc/html/rfc2616#section-5.1.2).144145This enables support constructing requests that would otherwise be unsupported.146147* URL paths with non-standard escaping applied.148* Forward proxy requests using an absolute URI.149* Tunneling proxy requests using `CONNECT` with hostname as the target.150* Server-wide `OPTIONS *` requests.151152Some examples:153154Using the 'target' extension to send requests without the standard path escaping rules...155156```python157# Typically a request to "https://www.example.com/test^path" would158# connect to "www.example.com" and send an HTTP/1.1 request like...159#160# GET /test%5Epath HTTP/1.1161#162# Using the target extension we can include the literal '^'...163#164# GET /test^path HTTP/1.1165#166# Note that requests must still be valid HTTP requests.167# For example including whitespace in the target will raise a `LocalProtocolError`.168extensions = {"target": b"/test^path"}169response = httpx.get("https://www.example.com", extensions=extensions)170```171172The `target` extension also allows server-wide `OPTIONS *` requests to be constructed...173174```python175# This will send the following request...176#177# CONNECT * HTTP/1.1178extensions = {"target": b"*"}179response = httpx.request("CONNECT", "https://www.example.com", extensions=extensions)180```181

Extensions docs (#3080)Tom Christiebefore adoptionc51af4b

lines 182–242why, one step back
182## Response Extensions
183184### `"http_version"`185186The HTTP version, as bytes. Eg. `b"HTTP/1.1"`.187188When using HTTP/1.1 the response line includes an explicit version, and the value of this key could feasibly be one of `b"HTTP/0.9"`, `b"HTTP/1.0"`, or `b"HTTP/1.1"`.189190When using HTTP/2 there is no further response versioning included in the protocol, and the value of this key will always be `b"HTTP/2"`.191192### `"reason_phrase"`193194The reason-phrase of the HTTP response, as bytes. For example `b"OK"`. Some servers may include a custom reason phrase, although this is not recommended.195196HTTP/2 onwards does not include a reason phrase on the wire.197198When no key is included, a default based on the status code may be used.199200### `"stream_id"`201202When HTTP/2 is being used the `"stream_id"` response extension can be accessed to determine the ID of the data stream that the response was sent on.203204### `"network_stream"`205206The `"network_stream"` extension allows developers to handle HTTP `CONNECT` and `Upgrade` requests, by providing an API that steps outside the standard request/response model, and can directly read or write to the network.207208The interface provided by the network stream:209210* `read(max_bytes, timeout = None) -> bytes`211* `write(buffer, timeout = None)`212* `close()`213* `start_tls(ssl_context, server_hostname = None, timeout = None) -> NetworkStream`214* `get_extra_info(info) -> Any`215216This API can be used as the foundation for working with HTTP proxies, WebSocket upgrades, and other advanced use-cases.217218See the [network backends documentation](https://www.encode.io/httpcore/network-backends/) for more information on working directly with network streams.219220**Extra network information**221222The network stream abstraction also allows access to various low-level information that may be exposed by the underlying socket:223224```python225response = httpx.get("https://www.example.com")226network_stream = response.extensions["network_stream"]227228client_addr = network_stream.get_extra_info("client_addr")229server_addr = network_stream.get_extra_info("server_addr")230print("Client address", client_addr)231print("Server address", server_addr)232```233234The socket SSL information is also available through this interface, although you need to ensure that the underlying connection is still open, in order to access it...235236```python237with httpx.stream("GET", "https://www.example.com") as response:238 network_stream = response.extensions["network_stream"]239240 ssl_object = network_stream.get_extra_info("ssl_object")241 print("TLS version", ssl_object.version())242```