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):
- CLI flags
- Environment variables
- TOML file (via
--configorH2CORN_CONFIG) - Built-in defaults
Unix listeners (unix:PATH) and the user/group/umask options are POSIX-only.
Raises:
| Type | Description |
|---|---|
TypeError | An option has the wrong Python type. |
ValueError | An option value or combination (for example, |
NotImplementedError | An option is unsupported on this platform (for example, |
ModuleNotFoundError |
|
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:
| Name | Type | Description | Default |
|---|---|---|---|
env | Mapping[str, str] | None | Mapping of environment variable names to values. Defaults to | None |
Raises:
| Type | Description |
|---|---|
ValueError | An unknown |
TypeError | A parsed value has the wrong Python type. |
NotImplementedError | An enabled option is unsupported on this platform. |
ModuleNotFoundError |
|
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:
| Name | Type | Description | Default |
|---|---|---|---|
data | Mapping[str, object] | Mapping of | required |
Raises:
| Type | Description |
|---|---|
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 |
|
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:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | PathLike[str] | Path to the TOML configuration file. | required |
Raises:
| Type | Description |
|---|---|
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 |
|
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:
| Name | Type | Description |
|---|---|---|
path | str | An exact ASCII request path or slash-delimited subtree ending in |
max_request_body_size | int | None | Maximum request-body bytes as an exact integer from |
timeout_request_body_idle | float | None | Maximum seconds without request-body data, or |
h2_timeout_response_stall | float | None | Maximum seconds response bytes may remain blocked by HTTP/2 peer flow control, or |
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:
| Type | Description |
|---|---|
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']