Skip to content

Config

Use Config to configure the server and RequestPolicy for path-specific limits. Constructor options are keyword-only. The Configuration reference lists their types, defaults, CLI flags, environment variables, TOML keys, and precedence. Option literal types are exported from h2corn.types.

Config

Immutable server configuration.

Configuration can be loaded with Config.from_env, Config.from_mapping, or Config.from_toml.

Every option is also exposed as a CLI flag and an H2CORN_* environment variable. The full list and defaults are documented in the configuration reference of the project documentation.

Resolution order (highest precedence first):

  1. CLI flags
  2. Environment variables
  3. TOML file (via --config or H2CORN_CONFIG)
  4. Built-in defaults

Unix listeners (unix:PATH) and the user/group/umask options are POSIX-only.

Raises:

TypeDescription
TypeError

An option has the wrong Python type.

ValueError

An option value or combination (for example, certfile without keyfile, bind with host/port, or TLS on a Unix listener) is invalid.

NotImplementedError

An option is unsupported on this platform (for example, reuse_port=True without SO_REUSEPORT or loop='uvloop' on Windows).

ModuleNotFoundError

loop='uvloop' is requested without the uvloop package installed.

Examples:

Configure an option without starting a server:

>>> config = Config(bind=('127.0.0.1:0',), access_log=False)
>>> (config.bind, config.access_log)
(('127.0.0.1:0',), False)

Invalid combinations fail during construction:

>>> Config(certfile='server.pem')
Traceback (most recent call last):
...
ValueError: certfile and keyfile must be configured together

from_envclassmethod

from_env(env: Mapping[str, str] | None = None) -> Self

Build a Config from H2CORN_* environment variables.

Each option's environment variable name is its field name in upper case, prefixed with H2CORN_ (for example, H2CORN_BIND, H2CORN_WORKERS, H2CORN_PROXY_HEADERS). Variables that are not set fall through to defaults. Unknown H2CORN_* names raise ValueError; variables outside that prefix are ignored.

The convenience pair H2CORN_HOST / H2CORN_PORT is accepted only when H2CORN_BIND is unset.

Parameters:

NameTypeDescriptionDefault
envMapping[str, str] | None

Mapping of environment variable names to values. Defaults to os.environ when None.

None

Raises:

TypeDescription
ValueError

An unknown H2CORN_* variable is present, a value cannot be parsed, or the resulting configuration is invalid.

TypeError

A parsed value has the wrong Python type.

NotImplementedError

An enabled option is unsupported on this platform.

ModuleNotFoundError

H2CORN_LOOP=uvloop is set without uvloop installed.

Examples:

Pass an explicit mapping so the process environment is not involved:

>>> config = Config.from_env(
...     {'H2CORN_BIND': '127.0.0.1:9000', 'H2CORN_WORKERS': '2'}
... )
>>> (config.bind, config.workers)
(('127.0.0.1:9000',), 2)

from_mappingclassmethod

from_mapping(data: Mapping[str, object]) -> Self

Build a Config from a plain mapping (e.g. parsed JSON or TOML).

Keys must match either a field name on Config or the convenience keys host/port. Unknown keys raise ValueError. String values are coerced through the same parsing rules as the matching environment variable; other values are checked against the option's accepted types.

Parameters:

NameTypeDescriptionDefault
dataMapping[str, object]

Mapping of Config field names (or host/port) to values.

required

Raises:

TypeDescription
ValueError

Unknown keys are present, a string value cannot be parsed, or the resulting configuration is invalid.

TypeError

A value has the wrong Python type.

NotImplementedError

An enabled option is unsupported on this platform.

ModuleNotFoundError

loop='uvloop' is requested without uvloop installed.

Examples:

String values use the same parsing rules as environment values:

>>> config = Config.from_mapping(
...     {'workers': '2', 'access_log': 'false'}
... )
>>> (config.workers, config.access_log)
(2, False)

from_tomlclassmethod

from_toml(path: str | PathLike[str]) -> Self

Build a Config from a TOML file.

The file uses top-level Config field names. Request policies use an array of tables. For example, save this as h2corn.toml:

bind = ["127.0.0.1:8000"]
workers = 4
proxy_headers = true
trusted_peers = ["127.0.0.1", "::1", "unix"]
forwarded_fields = ["for", "proto"]

[[request_policies]]
path = "/example.Chat/*"
max_request_body_size = 0
timeout_request_body_idle = 0

Load it with:

from h2corn import Config

config = Config.from_toml('h2corn.toml')

Parameters:

NameTypeDescriptionDefault
pathstr | PathLike[str]

Path to the TOML configuration file.

required

Raises:

TypeDescription
OSError

The file cannot be opened or read.

TOMLDecodeError

The file is not valid TOML.

ValueError

Unknown keys, invalid values, or invalid combinations are present.

TypeError

A value has the wrong Python type.

NotImplementedError

An enabled option is unsupported on this platform.

ModuleNotFoundError

loop='uvloop' is requested without uvloop installed.

RequestPolicydataclass

RequestPolicy(
    *,
    path: str,
    max_request_body_size: int | None = None,
    timeout_request_body_idle: float | None = None,
    h2_timeout_response_stall: float | None = None,
)

Path-specific body and HTTP/2 response-stall policy overrides.

Attributes:

NameTypeDescription
pathstr

An exact ASCII request path or slash-delimited subtree ending in /*. Queries are excluded from matching. Paths are compared case-sensitively and percent escapes are not decoded. /service/* matches /service/ and its descendants, not /service itself.

max_request_body_sizeint | None

Maximum request-body bytes as an exact integer from 0 through 18_446_744_073_709_551_615, or None to inherit Config.max_request_body_size. Use 0 to explicitly disable the cumulative size limit for matching paths. Unmatched native gRPC requests are exempt when Config.grpc is enabled; see Config.grpc.

timeout_request_body_idlefloat | None

Maximum seconds without request-body data, or None to inherit Config.timeout_request_body_idle. Use 0 to explicitly disable the idle timer for matching paths. Unmatched native gRPC requests are exempt when Config.grpc is enabled; see Config.grpc.

h2_timeout_response_stallfloat | None

Maximum seconds response bytes may remain blocked by HTTP/2 peer flow control, or None to inherit Config.h2_timeout_response_stall. Use 0 to explicitly disable the timer for matching paths.

A matching rule takes precedence over the native gRPC streaming defaults. Any omitted (None) field inherits the corresponding global Config setting, so overriding only max_request_body_size for /upload/* does not require duplicating timeouts. Native gRPC admission is still controlled by Config.grpc (when disabled, native gRPC receives HTTP 415 even if a path rule matches).

Construction accepts exact integers or floats for timeout seconds and normalizes them to floats. Booleans, non-finite numbers, and negative values are rejected. Config validation also rejects durations the runtime's monotonic clock cannot represent.

Raises:

TypeDescription
TypeError

A field has the wrong Python type.

ValueError

The path or a numeric field is outside its accepted range.

pathinstance-attribute

path: str

max_request_body_sizeclass-attributeinstance-attribute

max_request_body_size: int | None = None

timeout_request_body_idleclass-attributeinstance-attribute

timeout_request_body_idle: float | None = None

h2_timeout_response_stallclass-attributeinstance-attribute

h2_timeout_response_stall: float | None = None

ProxyProtocolModemodule-attribute

ProxyProtocolMode = Literal['off', 'v1', 'v2']

LifespanModemodule-attribute

LifespanMode = Literal['auto', 'on', 'off']

ClientCertModemodule-attribute

ClientCertMode = Literal['none', 'optional', 'required']

ForwardedFieldmodule-attribute

ForwardedField = Literal['for', 'proto', 'host', 'port', 'prefix', 'forwarded']

LoopImplmodule-attribute

LoopImpl = Literal['auto', 'asyncio', 'uvloop']

ServerHeaderModemodule-attribute

ServerHeaderMode = Literal['off', 'on', 'full']

LogFormatmodule-attribute

LogFormat = Literal['text', 'json']