Skip to main content

A Python library for real-time PostgreSQL event-driven cache invalidation.

Project description

🚀 PGCacheWatch - Supercharge Your Caching Strategy 🚀

CI pypi downloads versions


📚 Documentation: Explore the Docs 📖

🔍 Source Code: View on GitHub 💾


PGCacheWatch is the a Python library designed to propel your applications into a new realm of efficiency with real-time PostgreSQL event notifications for cache invalidation. Wave goodbye to stale data and hello to seamless cache management, bolstered performance powered by the robust backbone of PostgreSQL.

Example with FastAPI

PGCacheWatch integrates with FastAPI, empowering you to keep your application's data fresh and consistent by dynamically invalidating cache in line with database updates.

import contextlib
import typing

import asyncpg
from fastapi import FastAPI
from pgcachewatch import decorators, listeners, models, strategies

# Initialize a PGEventQueue listener to listen for database events.
listener = listeners.PGEventQueue()

@contextlib.asynccontextmanager
async def app_setup_teardown(_: FastAPI) -> typing.AsyncGenerator[None, None]:
    """
    Asynchronous context manager for FastAPI app setup and teardown.

    This context manager is used to establish and close the database connection
    at the start and end of the FastAPI application lifecycle, respectively.
    """
    # Establish a database connection using asyncpg.
    conn = await asyncpg.connect()
    # Connect the listener to the database using the specified channel.
    await listener.connect(conn)

    try:
        yield
    finally:
        await conn.close()  # Ensure the database connection is closed on app teardown.

# Create an instance of FastAPI, specifying the app setup and teardown actions.
APP = FastAPI(lifespan=app_setup_teardown)

# Decorate the cached_query function with cache invalidation logic.
@decorators.cache(
    strategy=strategies.Greedy(
        listener=listener,
        # Invalidate the cache only for 'update' operations on the database.
        predicate=lambda x: x.operation == "update",
    )
)
async def cached_query(user_id: int) -> dict[str, str]:
    """
    Simulates a database query that benefits from cache invalidation.

    This function is decorated to use PGCacheWatch's cache invalidation, ensuring
    that the data returned is up-to-date following any relevant 'update' operations
    on the database.
    """
    # Return a mock data response.
    return {"data": "query result"}

# Define a FastAPI route to fetch data, utilizing the cached_query function.
@APP.get("/data")
async def get_data(user_id: int) -> dict:
    """
    This endpoint uses the cached_query function to return data, demonstrating
    how cache invalidation can be integrated into a web application route.
    """
    # Fetch and return the data using the cached query function.
    return await cached_query(user_id)

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

PGCacheWatch-0.4.2.tar.gz (155.3 kB view details)

Uploaded Source

Built Distribution

PGCacheWatch-0.4.2-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file PGCacheWatch-0.4.2.tar.gz.

File metadata

  • Download URL: PGCacheWatch-0.4.2.tar.gz
  • Upload date:
  • Size: 155.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for PGCacheWatch-0.4.2.tar.gz
Algorithm Hash digest
SHA256 4bc8dffa7a4af54414ad1d045569d71e49f1e8ee343244a7dd7374fd375c6a27
MD5 0cd77ea392070e33951f2b971d16f6b1
BLAKE2b-256 4ddb400a704c49a82b8ac5bc65aa1f99872ee6538917c6f01f1db801333049bd

See more details on using hashes here.

File details

Details for the file PGCacheWatch-0.4.2-py3-none-any.whl.

File metadata

  • Download URL: PGCacheWatch-0.4.2-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for PGCacheWatch-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 237e08b5c15c4ae86bb2843875da5c4d24404cbb66e2b8dbfe19f9291fc723e5
MD5 f76fb263e860d3bc44a76202f5bcf1c6
BLAKE2b-256 74b24f3380b34afe5b91b6e311e2386b8719e9d2804c8c1b03e5e154113a5f43

See more details on using hashes here.

Supported by

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