persistent-cache-decorator


Namepersistent-cache-decorator JSON
Version 0.1.7 PyPI version JSON
download
home_page
SummaryA decorator for caching functions that provides persistence to JSON, pickle, or SQLite
upload_time2024-03-09 02:26:51
maintainer
docs_urlNone
author
requires_python>=3.8
license
keywords json sqlite cache decorator persistence pickle
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # persistent-cache-decorator

[![PyPI - Version](https://img.shields.io/pypi/v/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/FlavioAmurrioCS/persistent-cache-decorator/main.svg)](https://results.pre-commit.ci/latest/github/FlavioAmurrioCS/persistent-cache-decorator/main)

-----

**Table of Contents**

- [persistent-cache-decorator](#persistent-cache-decorator)
  - [Installation](#installation)
  - [Usage](#usage)
  - [Cached Property](#cached-property)
  - [Creating a custom cache backend](#creating-a-custom-cache-backend)
  - [License](#license)

## Installation

```console
pip install persistent-cache-decorator
```

## Usage
```python
from __future__ import annotations

import time

from persistent_cache.backend import CacheBackend
from persistent_cache.decorators import json_cache
from persistent_cache.decorators import persistent_cache


@persistent_cache(minutes=4)
def long_func(n: int) -> str:
    """Long Func Documentation."""
    # Long function
    time.sleep(n)
    return f"{n}"


# reveal_type(long_func)
# Runtime type is "_persistent_cache"
# <persistent_cache_decorator._persistent_cache object at 0x10468be50>

# Call function(takes 5 seconds)
long_func(5)
"5"
# Call function again (takes 0 seconds)
long_func(5)
"5"

# Bypass caching(takes 5 seconds)
long_func.no_cache_call(5)
"5"

# Call function again (takes 0 seconds)
long_func(5)
"5"
# Clear cache for this function
long_func.cache_clear()

# Call function(takes 5 seconds)
long_func(5)
```

## Cached Property
```python
from typing import NamedTuple  # noqa: E402
from persistent_cache.decorators import json_cached_property  # noqa: E402


# To cache instance methods, use the json_cache decorator you can do the following:
# Reference: https://www.youtube.com/watch?v=sVjtp6tGo0g
class Pet:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
        # creating the cache function this way will allow the cache to be cleared using the instance
        # It will also only use the arguments as the key
        self.online_information = json_cache(days=2)(self._online_information)

    def _online_information(self, source: str) -> int:
        # Something that takes a long time
        return len(source)


pet = Pet("Rex", 5)
pet.online_information(source="https://api.github.com/users/rex")
pet.online_information.cache_clear()


# NEW: or you can use the json_cached_property decorator to cache the result of a method
# This makes use of Python's Descriptors: https://www.youtube.com/watch?v=vBys0SwYvCQ
class Person(NamedTuple):
    name: str
    age: int

    # The decorator works with Namedtuples as well as with classes
    @json_cached_property(days=2)
    def online_information(self, source: str) -> int:
        # Something that takes a long time
        return len(source)


person = Person("John", 30)

# The following call will cache the result using the class instance as well as the arguments as the key  # noqa: E501
person.online_information(source="https://api.github.com/users/john")

# To clear the cache, use the method from the class directly
Person.online_information.cache_clear()
```

## Creating a custom cache backend

```python
from typing_extensions import Any  # noqa: E402
from typing import Callable  # noqa: E402
from persistent_cache.decorators import cache_decorator_factory  # noqa: E402
from typing import TYPE_CHECKING  # noqa: E402

if TYPE_CHECKING:
    import datetime
    from persistent_cache.decorators import _R


# Define a custom cache backend
class RedisCacheBackend(CacheBackend):
    def get_cache_or_call(  # type: ignore[empty-body]
        self,
        *,
        func: Callable[..., _R],
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
        lifespan: datetime.timedelta,
    ) -> _R:
        ...

    def del_func_cache(self, *, func: Callable[..., Any]) -> None:
        ...


# Singleton Instance
REDIS_CACHE_BACKEND = RedisCacheBackend()

# Quick way of defining a decorator. You can use this if you want multiple decorators with different cache durations.  # noqa: E501
redis_cache = cache_decorator_factory(backend=REDIS_CACHE_BACKEND)


@redis_cache(days=1)
def foo(time: float) -> float:
    from time import sleep

    sleep(time)
    return time
```

## License

`persistent-cache-decorator` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "persistent-cache-decorator",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "JSON,SQLite,cache,decorator,persistence,pickle",
    "author": "",
    "author_email": "Flavio Amurrio <25621374+FlavioAmurrioCS@users.noreply.github.com>",
    "download_url": "https://files.pythonhosted.org/packages/73/a2/e8d602a17e08fc903b8970466632628e8d4776503f2f56f31ed624a206cc/persistent_cache_decorator-0.1.7.tar.gz",
    "platform": null,
    "description": "# persistent-cache-decorator\n\n[![PyPI - Version](https://img.shields.io/pypi/v/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/persistent-cache-decorator.svg)](https://pypi.org/project/persistent-cache-decorator)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/FlavioAmurrioCS/persistent-cache-decorator/main.svg)](https://results.pre-commit.ci/latest/github/FlavioAmurrioCS/persistent-cache-decorator/main)\n\n-----\n\n**Table of Contents**\n\n- [persistent-cache-decorator](#persistent-cache-decorator)\n  - [Installation](#installation)\n  - [Usage](#usage)\n  - [Cached Property](#cached-property)\n  - [Creating a custom cache backend](#creating-a-custom-cache-backend)\n  - [License](#license)\n\n## Installation\n\n```console\npip install persistent-cache-decorator\n```\n\n## Usage\n```python\nfrom __future__ import annotations\n\nimport time\n\nfrom persistent_cache.backend import CacheBackend\nfrom persistent_cache.decorators import json_cache\nfrom persistent_cache.decorators import persistent_cache\n\n\n@persistent_cache(minutes=4)\ndef long_func(n: int) -> str:\n    \"\"\"Long Func Documentation.\"\"\"\n    # Long function\n    time.sleep(n)\n    return f\"{n}\"\n\n\n# reveal_type(long_func)\n# Runtime type is \"_persistent_cache\"\n# <persistent_cache_decorator._persistent_cache object at 0x10468be50>\n\n# Call function(takes 5 seconds)\nlong_func(5)\n\"5\"\n# Call function again (takes 0 seconds)\nlong_func(5)\n\"5\"\n\n# Bypass caching(takes 5 seconds)\nlong_func.no_cache_call(5)\n\"5\"\n\n# Call function again (takes 0 seconds)\nlong_func(5)\n\"5\"\n# Clear cache for this function\nlong_func.cache_clear()\n\n# Call function(takes 5 seconds)\nlong_func(5)\n```\n\n## Cached Property\n```python\nfrom typing import NamedTuple  # noqa: E402\nfrom persistent_cache.decorators import json_cached_property  # noqa: E402\n\n\n# To cache instance methods, use the json_cache decorator you can do the following:\n# Reference: https://www.youtube.com/watch?v=sVjtp6tGo0g\nclass Pet:\n    def __init__(self, name: str, age: int) -> None:\n        self.name = name\n        self.age = age\n        # creating the cache function this way will allow the cache to be cleared using the instance\n        # It will also only use the arguments as the key\n        self.online_information = json_cache(days=2)(self._online_information)\n\n    def _online_information(self, source: str) -> int:\n        # Something that takes a long time\n        return len(source)\n\n\npet = Pet(\"Rex\", 5)\npet.online_information(source=\"https://api.github.com/users/rex\")\npet.online_information.cache_clear()\n\n\n# NEW: or you can use the json_cached_property decorator to cache the result of a method\n# This makes use of Python's Descriptors: https://www.youtube.com/watch?v=vBys0SwYvCQ\nclass Person(NamedTuple):\n    name: str\n    age: int\n\n    # The decorator works with Namedtuples as well as with classes\n    @json_cached_property(days=2)\n    def online_information(self, source: str) -> int:\n        # Something that takes a long time\n        return len(source)\n\n\nperson = Person(\"John\", 30)\n\n# The following call will cache the result using the class instance as well as the arguments as the key  # noqa: E501\nperson.online_information(source=\"https://api.github.com/users/john\")\n\n# To clear the cache, use the method from the class directly\nPerson.online_information.cache_clear()\n```\n\n## Creating a custom cache backend\n\n```python\nfrom typing_extensions import Any  # noqa: E402\nfrom typing import Callable  # noqa: E402\nfrom persistent_cache.decorators import cache_decorator_factory  # noqa: E402\nfrom typing import TYPE_CHECKING  # noqa: E402\n\nif TYPE_CHECKING:\n    import datetime\n    from persistent_cache.decorators import _R\n\n\n# Define a custom cache backend\nclass RedisCacheBackend(CacheBackend):\n    def get_cache_or_call(  # type: ignore[empty-body]\n        self,\n        *,\n        func: Callable[..., _R],\n        args: tuple[Any, ...],\n        kwargs: dict[str, Any],\n        lifespan: datetime.timedelta,\n    ) -> _R:\n        ...\n\n    def del_func_cache(self, *, func: Callable[..., Any]) -> None:\n        ...\n\n\n# Singleton Instance\nREDIS_CACHE_BACKEND = RedisCacheBackend()\n\n# Quick way of defining a decorator. You can use this if you want multiple decorators with different cache durations.  # noqa: E501\nredis_cache = cache_decorator_factory(backend=REDIS_CACHE_BACKEND)\n\n\n@redis_cache(days=1)\ndef foo(time: float) -> float:\n    from time import sleep\n\n    sleep(time)\n    return time\n```\n\n## License\n\n`persistent-cache-decorator` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "A decorator for caching functions that provides persistence to JSON, pickle, or SQLite",
    "version": "0.1.7",
    "project_urls": {
        "Documentation": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator#readme",
        "Issues": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator/issues",
        "Source": "https://github.com/FlavioAmurrioCS/persistent-cache-decorator"
    },
    "split_keywords": [
        "json",
        "sqlite",
        "cache",
        "decorator",
        "persistence",
        "pickle"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d8ec135bafe1430c87c56914dfc94665ecf369b934419f6a191f5f9fa0a792ed",
                "md5": "bd92b6c9953e167ea0359c3638717353",
                "sha256": "e4c199138320f2068c44a6278487b06bb2e8f0f243f6f281235ad86740914fb3"
            },
            "downloads": -1,
            "filename": "persistent_cache_decorator-0.1.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bd92b6c9953e167ea0359c3638717353",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 13737,
            "upload_time": "2024-03-09T02:26:50",
            "upload_time_iso_8601": "2024-03-09T02:26:50.035580Z",
            "url": "https://files.pythonhosted.org/packages/d8/ec/135bafe1430c87c56914dfc94665ecf369b934419f6a191f5f9fa0a792ed/persistent_cache_decorator-0.1.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "73a2e8d602a17e08fc903b8970466632628e8d4776503f2f56f31ed624a206cc",
                "md5": "bff85ec2b8bd49274c9df6564bc2e5e3",
                "sha256": "11b50fa2b866fa278bdddf17fd133868f3133a2124fd4d9937e95a3460fd6080"
            },
            "downloads": -1,
            "filename": "persistent_cache_decorator-0.1.7.tar.gz",
            "has_sig": false,
            "md5_digest": "bff85ec2b8bd49274c9df6564bc2e5e3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 15036,
            "upload_time": "2024-03-09T02:26:51",
            "upload_time_iso_8601": "2024-03-09T02:26:51.646046Z",
            "url": "https://files.pythonhosted.org/packages/73/a2/e8d602a17e08fc903b8970466632628e8d4776503f2f56f31ed624a206cc/persistent_cache_decorator-0.1.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-09 02:26:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "FlavioAmurrioCS",
    "github_project": "persistent-cache-decorator#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "persistent-cache-decorator"
}
        
Elapsed time: 0.20141s