Skip to main content

Wardy Utils

Wardy Utils is a collection of general-purpose utilities designed to simplify and enhance your Python scripting experience. This library provides reusable components that can be integrated into your projects to save time and effort.

Installation

pip install wardy-utils

The base package only includes pydantic-settings. Install extras for additional functionality:

# Logging with Loguru
pip install wardy-utils[log]

# HTTP client with caching
pip install wardy-utils[web]

# Neon free-plan usage check
pip install wardy-utils[neon]

# Both
pip install wardy-utils[log,web]

Features

Logging (wardy-utils[log])

Flexible logging setup using Loguru, with optional Logfire integration for cloud logging and metrics.

Key features:

  • Simple setup for rotating file and stderr logging
  • Intercepts standard Python logging and redirects to Loguru
  • Optional Logfire integration for cloud log aggregation
  • Automatic instrumentation of available libraries (system-metrics, psycopg, httpx, sqlalchemy, redis, asyncpg)

Basic usage:

from wardy_utils.log import configure_logging, logger

# Set up logging to both stderr and a rotating file
configure_logging("myapp")

logger.info("Hello from Loguru!")

# Standard logging is also intercepted:
import logging
logging.warning("This will also go to Loguru!")

With Logfire cloud logging:

from wardy_utils.log import configure_logging, logger

# service_name defaults to the current working directory name
configure_logging("my-app")

# Or specify explicitly
configure_logging("my-app", service_name="my-app", environment="prod")

logger.info("This goes to Logfire too!")

Set WARDY_UTILS_LOG_LOGFIRE_TOKEN to enable Logfire. You must have logfire installed separately:

pip install logfire[system-metrics,psycopg,httpx]  # with desired extras

FastAPI:

from wardy_utils.log import instrument_fastapi

instrument_fastapi(app)  # no-op (returns False) without a Logfire token

Needs logfire[fastapi]. Healthchecks (/ping, /healthz) aren't traced by default; pass excluded_urls (regexes searched for in the full URL) to override.

Customization:

from wardy_utils.log import configure_logging, LogConfig

config = LogConfig(
    file_level="INFO",
    standard_format="[{time}] {level} - {message}",
    detail_format="{time} {file}:{line} {level} {message}",
    rotation="1 hour",
    retention="14 days",
)

configure_logging("my-app", service_name="my-app", config=config)

Environment variables:

Variable Description Default
WARDY_UTILS_LOG_LOGFIRE_TOKEN Token for Logfire cloud logging (disabled)
WARDY_UTILS_LOG_LOGFIRE_SERVICE_NAME Service name for Logfire (cwd name)
WARDY_UTILS_LOG_LOGFIRE_ENVIRONMENT Environment name for Logfire (cascaded)

Cascade behavior when not explicitly set:

  • LOGFIRE_SERVICE_NAME: Falls back to the current working directory name (e.g. beer-cloud)
  • LOGFIRE_ENVIRONMENT: Falls back to APP_ENVIRONMENT → REFLEX_ENV_MODE → NODE_ENV → ENVIRONMENT

HTTP Client (wardy-utils[web])

A high-level HTTP client built on httpx and hishel with built-in caching.

Basic usage:

from wardy_utils.web import cached_client

client = cached_client()
response = client.get("https://example.com")
print(response.text)

Pre-configured singletons:

from wardy_utils.web import sync_client, async_client

# Sync client with default settings
response = sync_client.get("https://example.com")

# Or use async
async def fetch():
    response = await async_client.get("https://example.com")

Available singletons:

  • sync_client: Default sync client (follows RFC 9111 cache headers)
  • sync_force_client: Sync client that ignores origin cache headers
  • async_client: Default async client (follows RFC 9111 cache headers)
  • async_force_client: Async client that ignores origin cache headers

Caching modes:

  • Default: the cache follows the origin's Cache-Control headers (RFC 9111).
  • force=True: origin headers are ignored. Successful (2xx, except 206) GET and HEAD responses are stored for ttl. Errors and redirects are never stored, so they are retried against the origin.
  • force=True, cache_redirects=True: also remembers 301/302/307/308 responses for ttl, so a repeat request to a redirecting URL sends nothing upstream. These are kept in process memory per client (up to 10,000), not in the sqlite cache, so they are lost on restart.

Was it cached, and when was it fetched?

from wardy_utils.web import cache_info

response = client.get("https://example.com")
info = cache_info(response)
info.from_cache  # True if the cache answered
info.fetched_at  # epoch seconds the content came off the network, or None

Every response that reaches the network is stamped with an X-Wardy-Fetched-At header. The header is stored with the cache entry, so fetched_at is the original fetch time even on a cache hit. cache_info also works for each hop in response.history.

Environment variables:

Variable Description Default
WARDY_UTILS_WEB_CACHE_DIR Directory for the sqlite cache file In-memory
WARDY_UTILS_WEB_CACHE_FILENAME Filename for the sqlite cache file wardy_cache_v2.db
WARDY_UTILS_WEB_CACHE_TTL Cache TTL in seconds 1800 (30 min)
WARDY_UTILS_WEB_TIMEOUT Per-operation request timeout in seconds 45
WARDY_UTILS_WEB_DEADLINE Total wall-clock deadline in seconds (async only) Off
WARDY_UTILS_WEB_FORCE_CACHE If truthy, ignore origin cache-control headers Disabled
WARDY_UTILS_WEB_CACHE_REDIRECTS With force, also remember redirects Disabled
WARDY_UTILS_WEB_BUST_EDGE_CACHE Add a unique _= query parameter to upstream requests (CDN bypass) Disabled
WARDY_UTILS_WEB_HTTP1 Enable or disable HTTP/1.1 Enabled
WARDY_UTILS_WEB_HTTP2 Enable or disable HTTP/2 Enabled

Proxy support: The client inherits proxy settings from standard http_proxy, https_proxy, and all_proxy environment variables. Proxied requests get the same caching, fetched_at stamp, edge-cache busting and redirect memory as direct ones.

Upgrading from wardy-utils 1.x (hishel 1.x) to 2.x (hishel 2.x)

wardy-utils 2.0 moves wardy_utils.web to hishel 2, which is a redesign of hishel. cached_client(), its options and the singletons keep the same signatures. These things change:

What 1.x 2.x
Was it a cache hit? response.extensions["hishel_from_cache"] cache_info(response).from_cache
When was it fetched? response.extensions["hishel_created_at"] cache_info(response).fetched_at (hishel 2 no longer records this)
Force mode internals client.policy is a hishel FilterPolicy; CacheOnlyOk / CacheOkOrRedirect filters client.rfc is False; the policy and filter classes are gone
What force mode stores 200 only Any 2xx except 206
Redirect caching 3xx stored in the sqlite cache 3xx remembered in process memory, lost on restart
hishel types SyncSqliteStorage, hishel.httpx.SyncCacheClient SqliteStorage, hishel.httpx.CacheClient (wardy_utils.web.SyncCacheClient still works)
Default cache file wardy_cache.db wardy_cache_v2.db. hishel 2 refuses to open a 1.x file, so delete the old one.
timeout= workaround wardy-utils re-injected the timeout hishel 1 dropped Not needed: hishel 2 passes the request through intact
Internal helpers Public names (build_client, resolve_config, ...) Private (_build_client, ...). Use cached_client().

If you set WARDY_UTILS_WEB_CACHE_FILENAME yourself, point it at a new file or delete the old one. Otherwise the first request raises hishel's "This database is a Hishel 1.x cache" error.

Neon usage (wardy-utils[neon])

Checks a Neon project's compute usage against the free plan's monthly CU-hour allowance, and projects the month-end total from the rate since the 1st. Calling Neon's API does not wake the database. Nothing is logged; HTTP and parsing errors (httpx.HTTPError, KeyError, ValueError) propagate for the caller to handle.

from wardy_utils.neon import get_usage

usage = await get_usage("my-project-id", api_key, allowance=100)
print(usage.cu_hours, usage.pct_used, usage.projected_cu_hours, usage.projected_pct)

With several worker processes, claim_usage_lock(path) lets only one of them call Neon: it returns an open lock file while held, or None if another process has it.

Requirements

  • Python 3.12 or higher
  • Linux or macOS (wardy_utils.neon uses fcntl for its usage lock)

License

This project is licensed under the MIT License.

Author

Created by Wardy Email: wardy3+gitlab@gmail.com

Metadata

Release files for wardy-utils 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wardy-utils 2.0.0
File Size Uploaded Provenance Actions
wardy_utils-2.0.0.tar.gz 17.7 kB Without provenance Details for wardy_utils-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for wardy-utils 2.0.0
File Interpreter ABI Platform Actions
wardy_utils-2.0.0-py3-none-any.whl Python 3 none any Details for wardy_utils-2.0.0-py3-none-any.whl

Total release size: 36.4 kB

Release files / wardy_utils-2.0.0.tar.gz

Download URL wardy_utils-2.0.0.tar.gz
Size 17.7 kB
Tags Source
SHA-256 checksum
How to use checksums
30a65adde05e3761156f2acf4cf7c9c4c87ff3fbdfd1b8c721e1aa962b5f89b5
BLAKE2b-256 checksum
How to use checksums
62f45e0946cae55e15935036a98717aa9460037577dd983271b8236f4fff1622
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / wardy_utils-2.0.0-py3-none-any.whl

Download URL wardy_utils-2.0.0-py3-none-any.whl
Size 18.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
13476cf1f74b8318e4f46af6ba1f2ba0ae0002b3264c121154782c589e1c20ff
BLAKE2b-256 checksum
How to use checksums
53e6a05b8b02c5d729a65d5de6c0351f5bedf10ba22ee1c5ea17cf8ede81cf77
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for wardy-utils 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page