Skip to main content

Cached niquests sessions with pluggable storage backends.

Project description

niquests-cache

Python versions PyPI - Version GitHub tag (with filter) License GitHub commits since latest release (by SemVer including pre-releases) CodeQL QA Tests Coverage Status Dependabot Documentation Status mypy uv pytest Ruff Downloads Stargazers pre-commit Prettier

@Tatsh Buy Me A Coffee Libera.Chat Mastodon Follow Patreon

Cached niquests sessions with pluggable storage backends. SQLite is the default; filesystem and in-memory backends are also built in.

Installation

pip install niquests-cache

Example usage

The cached_session() helper returns a CachedSession or AsyncCachedSession whose cache database is platformdirs.user_cache_path(app_name, appauthor=False) / 'http.sqlite'. If you omit app_name, niquests-cache is used. Only successful GET and HEAD responses are written; the default time-to-live is 10 minutes (expire_after= on the helper, or per-request— see below).

Sync helper (default app name and TTL):

from niquests_cache import cached_session

session = cached_session()
response = session.get('https://httpbin.org/get')
response.raise_for_status()

Custom application name for user_cache_path:

from niquests_cache import cached_session

session = cached_session(app_name='my-application')
response = session.get('https://httpbin.org/get')
response.raise_for_status()

Plain niquests session with no caching:

from niquests_cache import cached_session

session = cached_session(no_cache=True)

Construct CachedSession when you need an explicit cache name or TTL:

from datetime import timedelta
from pathlib import Path

from niquests_cache import CachedSession

with CachedSession(cache_name=Path('.cache') / 'http',
                   expire_after=timedelta(hours=1)) as session:
    response = session.get('https://httpbin.org/get')
    response.raise_for_status()

Async helper (use an async context manager):

import asyncio
from datetime import timedelta

from niquests_cache import cached_session

async def main() -> None:
    async with cached_session(aio=True, expire_after=timedelta(minutes=30)) as session:
        response = await session.get('https://httpbin.org/get')
        response.raise_for_status()

asyncio.run(main())

Or construct AsyncCachedSession directly:

import asyncio
from datetime import timedelta
from pathlib import Path

from niquests_cache import AsyncCachedSession

async def main() -> None:
    async with AsyncCachedSession(cache_name=Path('.cache') / 'http',
                                  expire_after=timedelta(hours=1)) as session:
        response = await session.get('https://httpbin.org/get')
        response.raise_for_status()

asyncio.run(main())

Choosing a backend

Pass backend= as one of the built-in aliases ('sqlite' (default), 'filesystem', 'memory') or a BaseBackend instance:

from niquests_cache import CachedSession
from niquests_cache.backends import FileCache, MemoryBackend

# Filesystem backend with custom cache directory:
session = CachedSession(backend='filesystem', cache_name='./fs-cache')

# In-memory (per-process) cache:
session = CachedSession(backend=MemoryBackend())

# FileCache with the pickle serializer (preserves binary content natively):
session = CachedSession(backend=FileCache('./fs-cache', serializer='pickle'))

The AsyncCachedSession uses aiosqlite for SQLite and anyio for filesystem I/O so async requests do not block the event loop.

Per-request controls

request() accepts expire_after, only_if_cached, refresh, and force_refresh per call:

# Bypass the cache read and replace any stored entry:
session.get('https://httpbin.org/get', force_refresh=True)

# Return a synthesised 504 if the entry is missing instead of going to the network:
session.get('https://httpbin.org/get', only_if_cached=True)

# Override the session-wide TTL for one request:
session.get('https://httpbin.org/get', expire_after=60)

Cache key behaviour

By default the cache key is sha256(method + url + '') — request headers are not part of the key. Pass match_headers=True to include all session/request headers, or match_headers=('Accept', 'Accept-Language') to include only the listed names. Strip query-string parameters from the key with ignored_parameters=('access_token', ...). Provide a key_fn= to replace key generation entirely.

Settings

All session settings live on the mutable session.settings dataclass (niquests_cache.settings.CacheSettings); change them at runtime, for example session.settings.expire_after = 360 or session.settings.read_only = True. Use with session.cache_disabled(): to suspend caching for a block.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

niquests_cache-0.2.0.tar.gz (21.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

niquests_cache-0.2.0-py3-none-any.whl (18.0 kB view details)

Uploaded Python 3

File details

Details for the file niquests_cache-0.2.0.tar.gz.

File metadata

  • Download URL: niquests_cache-0.2.0.tar.gz
  • Upload date:
  • Size: 21.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for niquests_cache-0.2.0.tar.gz
Algorithm Hash digest
SHA256 321beb3143201d10180164f3c5e10172f0fc869394c6a2f4e7737e209cb9aa6a
MD5 bd38914168bd3592c8a2844c782b8fa3
BLAKE2b-256 386fd0df38bc28981633469b847aafda0e56285971defc067473b9dfc8c8d82c

See more details on using hashes here.

Provenance

The following attestation bundles were made for niquests_cache-0.2.0.tar.gz:

Publisher: publish.yml on Tatsh/niquests-cache

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file niquests_cache-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: niquests_cache-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 18.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for niquests_cache-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 39cd46aa07b93ff2c695208ef8b650114d206303ae92460bc489fe0263a3a8a8
MD5 6d407ef8710b9429bd46cc6b719c2eb5
BLAKE2b-256 48aa8fec7f0d29d7d8cc4438b20203f9ffffa19c1acafa3f94abb881daa0b884

See more details on using hashes here.

Provenance

The following attestation bundles were made for niquests_cache-0.2.0-py3-none-any.whl:

Publisher: publish.yml on Tatsh/niquests-cache

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page