The transport options of @clickhouse/client a ClickhouseClientConfig
takes, under their createClient names: compression, keep_alive,
tls, log and json (with max_open_connections,
use_multipart_params and use_multipart_params_auto, plain fields of
the config). Each is checked when the config is made and parsed here into
what the driver and the httpx client use.
compression:{"response": True}asks the server for a gzip response (enable_http_compression=1,Accept-Encoding);{"response": {"codec": "zstd"}}names the codec.{"request": True}gzips the bodies of inserts, commands andexec;{"request": {"codec": "br", "quality": 4}}picks the codec and its level (levelfor gzip and zstd,qualityfor Brotli, 4 by default). A zstd request body needs Python 3.14 (compression.zstd), Brotli thebrotliextra; on the httpx clientmakecreates, a zstd response needszstandardand a Brotli one thebrotliextra.keep_alive:enabled(True) andidle_socket_ttl, how long an idle connection is kept (2500 ms;0keeps it until the server closes it).tls:{"ca_cert": pem}to trust a CA, withcertandkeyfor a client certificate; on anhttpsURL the credentials then go inX-ClickHouse-User/X-ClickHouse-Key(andX-ClickHouse-SSL-Certificate-Auth: onwith a certificate).log:{"level": "WARN"}, the least severe of the client's own logs that are written, through the fiber's loggers.json:{"parse": ..., "stringify": ...}read result rows and write inserted rows.
keep_alive, max_open_connections and tls configure the httpx
client make creates, and have no effect on an http_client given in
the config (as on @clickhouse/client's http_agent).
Values#
| Attribute | Type | Description |
|---|---|---|
LOG_LEVELS | dict[LogLevel, int] = {'TRACE': 0, 'DEBUG': 1, 'INFO': 2, 'WARN': 3, 'ERROR': 4, 'OFF': 127} |
|
Types#
| Type | Definition | Description |
|---|---|---|
CompressionCodec | type CompressionCodec = Literal['gzip', 'zstd', 'br'] | A codec |
RequestCompression | type RequestCompression = GzipRequestCompression | ZstdRequestCompression | BrotliRequestCompression | |
Tls | type Tls = BasicTls | MutualTls | |
LogLevel | type LogLevel = Literal['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'OFF'] |
Classes#
Functions#
json_handling#
json_handling(given) -> Json| Parameter | Type | Description |
|---|---|---|
given | JsonHandling | None |
Returns Json
def json_handling(given: JsonHandling | None) -> Json:
given = given or {}
return Json(given.get("parse", _json_text.parse), given.get("stringify"))request_codec#
request_codec(value) -> RequestCodec | NonenormalizeRequestCompression and ensureRequestCodecSupported.
| Parameter | Type | Description |
|---|---|---|
value | bool | RequestCompression | None |
Returns RequestCodec | None
def request_codec(value: bool | RequestCompression | None) -> RequestCodec | None:
"""``normalizeRequestCompression`` and ``ensureRequestCodecSupported``."""
if not value:
return None
if value is True:
return RequestCodec("gzip")
codec = cast("object", value.get("codec"))
match codec:
case "gzip" | "zstd":
found = RequestCodec(
"gzip" if codec == "gzip" else "zstd", cast("int | None", value.get("level"))
)
case "br":
found = RequestCodec("br", cast("int | None", value.get("quality")))
case _:
raise _unknown_codec(codec, "request")
if found.codec == "zstd" and not _has_module("compression.zstd"):
raise _zstd_unsupported("compressing needs Python 3.14 (`compression.zstd`)")
if found.codec == "br":
import pyfect.http._brotli # noqa: F401 # pyright: ignore[reportUnusedImport]
return foundresponse_codec#
response_codec(value, *, default_client) -> CompressionCodec | NonenormalizeResponseCompression and ensureResponseCodecSupported:
on the httpx client make creates, the codec must be one httpx can
decode.
| Parameter | Type | Description |
|---|---|---|
value | bool | ResponseCompression | None | |
default_client | bool |
Returns CompressionCodec | None
def response_codec(
value: bool | ResponseCompression | None, *, default_client: bool
) -> CompressionCodec | None:
"""``normalizeResponseCompression`` and ``ensureResponseCodecSupported``:
on the httpx client ``make`` creates, the codec must be one httpx can
decode."""
if not value:
return None
if value is True:
return "gzip"
codec = cast("object", value.get("codec"))
if codec not in _CODECS:
raise _unknown_codec(codec, "response")
found: CompressionCodec = codec
if default_client and found == "zstd" and not _has_module("zstandard"):
raise _zstd_unsupported("httpx decompresses zstd with the `zstandard` package")
if (
default_client
and found == "br"
and not _has_module("brotlicffi")
and not _has_module("brotli")
):
raise ImportError(
"Brotli responses need the 'brotli' extra for httpx to decompress them: "
"pip install 'pyfect-dev[brotli]'"
)
return foundtls_context#
tls_context(tls) -> TlsContextAn SSL context trusting ca_cert (only it, as Node's ca), with
the client certificate when cert and key are given.
| Parameter | Type | Description |
|---|---|---|
tls | Tls |
Returns TlsContext
def tls_context(tls: Tls) -> TlsContext:
"""An SSL context trusting ``ca_cert`` (only it, as Node's ``ca``), with
the client certificate when ``cert`` and ``key`` are given."""
context = ssl.create_default_context(cadata=tls["ca_cert"].decode("ascii"))
cert, key = tls.get("cert"), tls.get("key")
mutual = cert is not None and key is not None
if mutual:
# ``ssl`` loads a certificate chain only from files.
with tempfile.TemporaryDirectory() as directory:
cert_path = os.path.join(directory, "cert.pem")
key_path = os.path.join(directory, "key.pem")
for path, data in ((cert_path, cert), (key_path, key)):
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as file:
file.write(cast("bytes", data))
context.load_cert_chain(cert_path, key_path)
return TlsContext(context, mutual)url_boolean#
url_boolean(key, value) -> boolbooleanConfigURLValue.
| Parameter | Type | Description |
|---|---|---|
key | str | |
value | str |
Returns bool
def url_boolean(key: str, value: str) -> bool:
"""``booleanConfigURLValue``."""
trimmed = value.strip()
if trimmed in ("true", "1"):
return True
if trimmed in ("false", "0"):
return False
raise ValueError(
f'"{key}" has invalid boolean value: {trimmed}. Expected one of: 0, 1, true, false.'
)url_number#
url_number(key, value, minimum) -> floatnumberConfigURLValue: read as JavaScript's Number.
| Parameter | Type | Description |
|---|---|---|
key | str | |
value | str | |
minimum | float |
Returns float
def url_number(key: str, value: str, minimum: float) -> float:
"""``numberConfigURLValue``: read as JavaScript's ``Number``."""
import math
from pyfect.schema.getter._coerce import to_number
trimmed = value.strip()
number = to_number(trimmed)
if math.isnan(number):
raise ValueError(f'"{key}" has invalid numeric value: {trimmed}')
if number < minimum:
raise ValueError(f'"{key}" value {trimmed} is less than min allowed {minimum:g}')
return numberurl_log_level#
url_log_level(key, value) -> LogLevelenumConfigURLValue over ClickHouseLogLevel.
| Parameter | Type | Description |
|---|---|---|
key | str | |
value | str |
Returns LogLevel
def url_log_level(key: str, value: str) -> LogLevel:
"""``enumConfigURLValue`` over ``ClickHouseLogLevel``."""
trimmed = value.strip()
if trimmed not in LOG_LEVELS:
raise ValueError(
f'"{key}" has invalid value: {trimmed}. Expected one of: {", ".join(LOG_LEVELS)}.'
)
return trimmedform_encoded_length#
form_encoded_length(entries) -> intnew URLSearchParams(entries).toString().length.
| Parameter | Type | Description |
|---|---|---|
entries | list[tuple[str, str]] |
Returns int
def form_encoded_length(entries: list[tuple[str, str]]) -> int:
"""``new URLSearchParams(entries).toString().length``."""
total = max(len(entries) - 1, 0)
for name, value in entries:
for text in (name, value):
total += sum(1 if c in _SAFE_FORM else 3 * len(text_encode(c)) for c in text)
total += 1
return total