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.1.tar.gz (22.9 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.1-py3-none-any.whl (19.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: niquests_cache-0.2.1.tar.gz
  • Upload date:
  • Size: 22.9 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.1.tar.gz
Algorithm Hash digest
SHA256 2e201ab7e8c3ba1cb7f79f48ed99083fa7725305536c1d1a58ad6388db419ca6
MD5 774386ea57d64f873655c93d159e3c49
BLAKE2b-256 0c1b420574085f726e310de07eaf4693921498e4ce1faaeddcdae97ccefae65a

See more details on using hashes here.

Provenance

The following attestation bundles were made for niquests_cache-0.2.1.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.1-py3-none-any.whl.

File metadata

  • Download URL: niquests_cache-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 19.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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e1226b89c413291cdd5586e4b44600906126f7820fa7b444d0cd1c46523b40ea
MD5 307553d900c0fb6ec74ebedc065e4365
BLAKE2b-256 d605e2584e492b9b44f932d155a504035d5751e352c683a94f7a85bf9f496008

See more details on using hashes here.

Provenance

The following attestation bundles were made for niquests_cache-0.2.1-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