py-cachify 1.1.2__tar.gz → 2.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py_cachify-2.0.0/PKG-INFO +191 -0
- py_cachify-2.0.0/README.md +159 -0
- py_cachify-2.0.0/py_cachify/__init__.py +32 -0
- py_cachify-2.0.0/py_cachify/_backend/_cached.py +105 -0
- py_cachify-1.1.2/py_cachify/backend/clients.py → py_cachify-2.0.0/py_cachify/_backend/_clients.py +0 -2
- py_cachify-1.1.2/py_cachify/backend/exceptions.py → py_cachify-2.0.0/py_cachify/_backend/_exceptions.py +0 -3
- py_cachify-2.0.0/py_cachify/_backend/_helpers.py +70 -0
- py_cachify-1.1.2/py_cachify/backend/lib.py → py_cachify-2.0.0/py_cachify/_backend/_lib.py +30 -12
- py_cachify-2.0.0/py_cachify/_backend/_lock.py +303 -0
- py_cachify-2.0.0/py_cachify/_backend/_types/_common.py +64 -0
- py_cachify-2.0.0/py_cachify/_backend/_types/_lock_wrap.py +46 -0
- py_cachify-2.0.0/py_cachify/_backend/_types/_reset_wrap.py +42 -0
- py_cachify-2.0.0/py_cachify/py.typed +0 -0
- {py_cachify-1.1.2 → py_cachify-2.0.0}/pyproject.toml +42 -24
- py_cachify-1.1.2/PKG-INFO +0 -105
- py_cachify-1.1.2/README.md +0 -84
- py_cachify-1.1.2/py_cachify/__init__.py +0 -20
- py_cachify-1.1.2/py_cachify/asyncio.py +0 -6
- py_cachify-1.1.2/py_cachify/backend/cached.py +0 -82
- py_cachify-1.1.2/py_cachify/backend/helpers.py +0 -34
- py_cachify-1.1.2/py_cachify/backend/lock.py +0 -125
- py_cachify-1.1.2/py_cachify/backend/types.py +0 -25
- py_cachify-1.1.2/py_cachify/sync.py +0 -6
- {py_cachify-1.1.2 → py_cachify-2.0.0}/LICENSE +0 -0
- {py_cachify-1.1.2/py_cachify/backend → py_cachify-2.0.0/py_cachify/_backend}/__init__.py +0 -0
- /py_cachify-1.1.2/py_cachify/py.typed → /py_cachify-2.0.0/py_cachify/_backend/_types/__init__.py +0 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: py-cachify
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Distributed locks, caching, and locking decorators at hand
|
|
5
|
+
Home-page: https://github.com/EzyGang/py-cachify
|
|
6
|
+
License: MIT
|
|
7
|
+
Author: Galtozzy
|
|
8
|
+
Author-email: galtozzy+git@gmail.com
|
|
9
|
+
Requires-Python: >=3.8,<4.0
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Information Technology
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
24
|
+
Classifier: Topic :: Software Development
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Dist: typing-extensions (>=4.12.2,<5.0.0)
|
|
29
|
+
Project-URL: Repository, https://github.com/EzyGang/py-cachify
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Py-Cachify
|
|
33
|
+
|
|
34
|
+
<p align="center">
|
|
35
|
+
<a href="https://opensource.org/licenses/MIT" target="_blank">
|
|
36
|
+
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
|
|
37
|
+
</a>
|
|
38
|
+
<a href="https://badge.fury.io/py/py-cachify" target="_blank">
|
|
39
|
+
<img src="https://badge.fury.io/py/py-cachify.svg" alt="PyPI version">
|
|
40
|
+
</a>
|
|
41
|
+
<a href="https://py-cachify.readthedocs.io/en/latest/?badge=latest" target="_blank">
|
|
42
|
+
<img src="https://readthedocs.org/projects/py-cachify/badge/?version=latest" alt="Documentation Status">
|
|
43
|
+
</a>
|
|
44
|
+
</p>
|
|
45
|
+
<p align="center">
|
|
46
|
+
<a href="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" target="_blank">
|
|
47
|
+
<img src="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" alt="Pre-build checks and Tests">
|
|
48
|
+
</a>
|
|
49
|
+
<a href="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" target="_blank">
|
|
50
|
+
<img src="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" alt="Tests Status">
|
|
51
|
+
</a>
|
|
52
|
+
<a href="https://coveralls.io/github/EzyGang/py-cachify?branch=main" target="_blank">
|
|
53
|
+
<img src="https://coveralls.io/repos/github/EzyGang/py-cachify/badge.png?branch=main" alt="Coverage Status">
|
|
54
|
+
</a>
|
|
55
|
+
<a href="https://sonarcloud.io/summary/new_code?id=EzyGang_py-cachify" target="_blank">
|
|
56
|
+
<img src="https://sonarcloud.io/api/project_badges/measure?project=EzyGang_py-cachify&metric=reliability_rating" alt="Reliability Rating">
|
|
57
|
+
</a>
|
|
58
|
+
</p>
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
**Documentation**: <a href="https://py-cachify.readthedocs.io/latest/" target="_blank">https://py-cachify.readthedocs.io/latest/</a>
|
|
63
|
+
|
|
64
|
+
**Source Code**: <a href="https://github.com/EzyGang/py-cachify" target="_blank">https://github.com/EzyGang/py-cachify</a>
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
py-cachify is a small library that provides useful cache-based utilities (caching, distributed locks) that are
|
|
69
|
+
enhanced versions of those provided by similar packages.
|
|
70
|
+
|
|
71
|
+
py-cachify works well in both sync and async environments, has 100% test coverage, is fully type annotated,
|
|
72
|
+
is backend agnostic (you can provide your own client as long as it matches the signature), and supports Python from 3.8 and upward.
|
|
73
|
+
|
|
74
|
+
It offers distributed (cache-based) locks and decorators to lock function executions,
|
|
75
|
+
and also caching utilities and decorators for storing results in the cache.
|
|
76
|
+
|
|
77
|
+
The key features are:
|
|
78
|
+
|
|
79
|
+
* **Intuitive to write**: Great editor support. When applying decorators your IDE will still be able to autocomplete and highlight inline errors for applied functions.
|
|
80
|
+
* **Fully type annotated**: You don't have to constantly look into the docs. Everything is type annotated and easy to understand out of the box.
|
|
81
|
+
* **Short**: Minimize code duplication. Add just one line of code to implement a cache or lock on your function.
|
|
82
|
+
* **Start simple**: The simplest example adds only a couple of lines of code: initialize a library and use the needed utility.
|
|
83
|
+
* **Backend agnostic**: Use whatever cache-backend you want to use. Py-Cachify is not forcing you into anything.
|
|
84
|
+
* **Test coverage**: Has 100% test coverage and supports Python 3.8+
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Table of Contents
|
|
89
|
+
|
|
90
|
+
- [Installation](#installation)
|
|
91
|
+
- [How to use](#how-to-use)
|
|
92
|
+
- [Basic examples](#basic-examples)
|
|
93
|
+
- [Contributing](#contributing)
|
|
94
|
+
- [License](#license)
|
|
95
|
+
|
|
96
|
+
## Installation
|
|
97
|
+
|
|
98
|
+
<!-- termynal -->
|
|
99
|
+
```bash
|
|
100
|
+
$ pip install py-cachify
|
|
101
|
+
|
|
102
|
+
---> 100%
|
|
103
|
+
Successfully installed py-cachify
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## How to use
|
|
107
|
+
|
|
108
|
+
You can read more in-depth tutorials [here](https://py-cachify.readthedocs.io/latest/tutorial/).
|
|
109
|
+
|
|
110
|
+
First, to start working with the library, you will have to initialize it by using the provided `init_cachify` function:
|
|
111
|
+
```python
|
|
112
|
+
from py_cachify import init_cachify
|
|
113
|
+
|
|
114
|
+
init_cachify()
|
|
115
|
+
```
|
|
116
|
+
By default, it will use an in-memory cache.
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
If you want to use Redis:
|
|
120
|
+
```python
|
|
121
|
+
from py_cachify import init_cachify
|
|
122
|
+
from redis.asyncio import from_url as async_from_url
|
|
123
|
+
from redis import from_url
|
|
124
|
+
|
|
125
|
+
init_cachify(sync_client=from_url(redis_url), async_client=async_from_url(async_redis_client))
|
|
126
|
+
```
|
|
127
|
+
Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async.
|
|
128
|
+
|
|
129
|
+
Once initialized you can use everything that the library provides straight up without being worried about managing the cache yourself.
|
|
130
|
+
|
|
131
|
+
❗ If you forgot to call `init_cachify` the `CachifyInitError` will be raised during runtime.
|
|
132
|
+
|
|
133
|
+
## Basic examples
|
|
134
|
+
|
|
135
|
+
### Caching
|
|
136
|
+
|
|
137
|
+
Caching by using `@cached` decorator utilizing the flexibility of a dynamic key:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
# Cache the result of the following function with dynamic key
|
|
141
|
+
@cached(key='sum_two-{a}-{b}')
|
|
142
|
+
async def sum_two(a: int, b: int) -> int:
|
|
143
|
+
# Let's put print here to see what was the function called with
|
|
144
|
+
print(f'Called with {a} {b}')
|
|
145
|
+
return a + b
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Read more about `@cached` [here](https://py-cachify.readthedocs.io/latest/reference/cached/).
|
|
149
|
+
|
|
150
|
+
### Locking
|
|
151
|
+
|
|
152
|
+
Locking through context manager:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from py_cachify import lock
|
|
156
|
+
|
|
157
|
+
# Use it within an asynchronous context
|
|
158
|
+
async with lock('resource_key'):
|
|
159
|
+
# Your critical section here
|
|
160
|
+
print('Critical section code')
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# Use it within a synchronous context
|
|
164
|
+
with lock('resource_key'):
|
|
165
|
+
# Your critical section here
|
|
166
|
+
print('Critical section code')
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Locking via decorator:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
|
|
173
|
+
from py_cachify import lock
|
|
174
|
+
|
|
175
|
+
@lock(key='critical_function_lock-{arg}', nowait=False, timeout=10)
|
|
176
|
+
def critical_function(arg: int) -> None:
|
|
177
|
+
# critical code
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Read more about `lock` [here](https://py-cachify.readthedocs.io/latest/reference/lock/).
|
|
181
|
+
|
|
182
|
+
For a more detailed tutorial visit [Tutorial](https://py-cachify.readthedocs.io/latest/tutorial/) or [full API reference](https://py-cachify.readthedocs.io/latest/reference).
|
|
183
|
+
|
|
184
|
+
## Contributing
|
|
185
|
+
|
|
186
|
+
If you'd like to contribute, please first discuss the changes using Issues, and then don't hesitate to shoot a PR which will be reviewed shortly.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
This project is licensed under the MIT License - see the [LICENSE](https://github.com/EzyGang/py-cachify/blob/main/LICENSE) file for details.
|
|
191
|
+
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# Py-Cachify
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://opensource.org/licenses/MIT" target="_blank">
|
|
5
|
+
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
|
|
6
|
+
</a>
|
|
7
|
+
<a href="https://badge.fury.io/py/py-cachify" target="_blank">
|
|
8
|
+
<img src="https://badge.fury.io/py/py-cachify.svg" alt="PyPI version">
|
|
9
|
+
</a>
|
|
10
|
+
<a href="https://py-cachify.readthedocs.io/en/latest/?badge=latest" target="_blank">
|
|
11
|
+
<img src="https://readthedocs.org/projects/py-cachify/badge/?version=latest" alt="Documentation Status">
|
|
12
|
+
</a>
|
|
13
|
+
</p>
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" target="_blank">
|
|
16
|
+
<img src="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" alt="Pre-build checks and Tests">
|
|
17
|
+
</a>
|
|
18
|
+
<a href="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" target="_blank">
|
|
19
|
+
<img src="https://github.com/EzyGang/py-cachify/actions/workflows/integration-tests.yml/badge.svg" alt="Tests Status">
|
|
20
|
+
</a>
|
|
21
|
+
<a href="https://coveralls.io/github/EzyGang/py-cachify?branch=main" target="_blank">
|
|
22
|
+
<img src="https://coveralls.io/repos/github/EzyGang/py-cachify/badge.png?branch=main" alt="Coverage Status">
|
|
23
|
+
</a>
|
|
24
|
+
<a href="https://sonarcloud.io/summary/new_code?id=EzyGang_py-cachify" target="_blank">
|
|
25
|
+
<img src="https://sonarcloud.io/api/project_badges/measure?project=EzyGang_py-cachify&metric=reliability_rating" alt="Reliability Rating">
|
|
26
|
+
</a>
|
|
27
|
+
</p>
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
**Documentation**: <a href="https://py-cachify.readthedocs.io/latest/" target="_blank">https://py-cachify.readthedocs.io/latest/</a>
|
|
32
|
+
|
|
33
|
+
**Source Code**: <a href="https://github.com/EzyGang/py-cachify" target="_blank">https://github.com/EzyGang/py-cachify</a>
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
py-cachify is a small library that provides useful cache-based utilities (caching, distributed locks) that are
|
|
38
|
+
enhanced versions of those provided by similar packages.
|
|
39
|
+
|
|
40
|
+
py-cachify works well in both sync and async environments, has 100% test coverage, is fully type annotated,
|
|
41
|
+
is backend agnostic (you can provide your own client as long as it matches the signature), and supports Python from 3.8 and upward.
|
|
42
|
+
|
|
43
|
+
It offers distributed (cache-based) locks and decorators to lock function executions,
|
|
44
|
+
and also caching utilities and decorators for storing results in the cache.
|
|
45
|
+
|
|
46
|
+
The key features are:
|
|
47
|
+
|
|
48
|
+
* **Intuitive to write**: Great editor support. When applying decorators your IDE will still be able to autocomplete and highlight inline errors for applied functions.
|
|
49
|
+
* **Fully type annotated**: You don't have to constantly look into the docs. Everything is type annotated and easy to understand out of the box.
|
|
50
|
+
* **Short**: Minimize code duplication. Add just one line of code to implement a cache or lock on your function.
|
|
51
|
+
* **Start simple**: The simplest example adds only a couple of lines of code: initialize a library and use the needed utility.
|
|
52
|
+
* **Backend agnostic**: Use whatever cache-backend you want to use. Py-Cachify is not forcing you into anything.
|
|
53
|
+
* **Test coverage**: Has 100% test coverage and supports Python 3.8+
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Table of Contents
|
|
58
|
+
|
|
59
|
+
- [Installation](#installation)
|
|
60
|
+
- [How to use](#how-to-use)
|
|
61
|
+
- [Basic examples](#basic-examples)
|
|
62
|
+
- [Contributing](#contributing)
|
|
63
|
+
- [License](#license)
|
|
64
|
+
|
|
65
|
+
## Installation
|
|
66
|
+
|
|
67
|
+
<!-- termynal -->
|
|
68
|
+
```bash
|
|
69
|
+
$ pip install py-cachify
|
|
70
|
+
|
|
71
|
+
---> 100%
|
|
72
|
+
Successfully installed py-cachify
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## How to use
|
|
76
|
+
|
|
77
|
+
You can read more in-depth tutorials [here](https://py-cachify.readthedocs.io/latest/tutorial/).
|
|
78
|
+
|
|
79
|
+
First, to start working with the library, you will have to initialize it by using the provided `init_cachify` function:
|
|
80
|
+
```python
|
|
81
|
+
from py_cachify import init_cachify
|
|
82
|
+
|
|
83
|
+
init_cachify()
|
|
84
|
+
```
|
|
85
|
+
By default, it will use an in-memory cache.
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
If you want to use Redis:
|
|
89
|
+
```python
|
|
90
|
+
from py_cachify import init_cachify
|
|
91
|
+
from redis.asyncio import from_url as async_from_url
|
|
92
|
+
from redis import from_url
|
|
93
|
+
|
|
94
|
+
init_cachify(sync_client=from_url(redis_url), async_client=async_from_url(async_redis_client))
|
|
95
|
+
```
|
|
96
|
+
Normally you wouldn't have to use both sync and async clients since an application usually works in a single mode i.e. sync/async.
|
|
97
|
+
|
|
98
|
+
Once initialized you can use everything that the library provides straight up without being worried about managing the cache yourself.
|
|
99
|
+
|
|
100
|
+
❗ If you forgot to call `init_cachify` the `CachifyInitError` will be raised during runtime.
|
|
101
|
+
|
|
102
|
+
## Basic examples
|
|
103
|
+
|
|
104
|
+
### Caching
|
|
105
|
+
|
|
106
|
+
Caching by using `@cached` decorator utilizing the flexibility of a dynamic key:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
# Cache the result of the following function with dynamic key
|
|
110
|
+
@cached(key='sum_two-{a}-{b}')
|
|
111
|
+
async def sum_two(a: int, b: int) -> int:
|
|
112
|
+
# Let's put print here to see what was the function called with
|
|
113
|
+
print(f'Called with {a} {b}')
|
|
114
|
+
return a + b
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Read more about `@cached` [here](https://py-cachify.readthedocs.io/latest/reference/cached/).
|
|
118
|
+
|
|
119
|
+
### Locking
|
|
120
|
+
|
|
121
|
+
Locking through context manager:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from py_cachify import lock
|
|
125
|
+
|
|
126
|
+
# Use it within an asynchronous context
|
|
127
|
+
async with lock('resource_key'):
|
|
128
|
+
# Your critical section here
|
|
129
|
+
print('Critical section code')
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# Use it within a synchronous context
|
|
133
|
+
with lock('resource_key'):
|
|
134
|
+
# Your critical section here
|
|
135
|
+
print('Critical section code')
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Locking via decorator:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
|
|
142
|
+
from py_cachify import lock
|
|
143
|
+
|
|
144
|
+
@lock(key='critical_function_lock-{arg}', nowait=False, timeout=10)
|
|
145
|
+
def critical_function(arg: int) -> None:
|
|
146
|
+
# critical code
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Read more about `lock` [here](https://py-cachify.readthedocs.io/latest/reference/lock/).
|
|
150
|
+
|
|
151
|
+
For a more detailed tutorial visit [Tutorial](https://py-cachify.readthedocs.io/latest/tutorial/) or [full API reference](https://py-cachify.readthedocs.io/latest/reference).
|
|
152
|
+
|
|
153
|
+
## Contributing
|
|
154
|
+
|
|
155
|
+
If you'd like to contribute, please first discuss the changes using Issues, and then don't hesitate to shoot a PR which will be reviewed shortly.
|
|
156
|
+
|
|
157
|
+
## License
|
|
158
|
+
|
|
159
|
+
This project is licensed under the MIT License - see the [LICENSE](https://github.com/EzyGang/py-cachify/blob/main/LICENSE) file for details.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from ._backend._cached import async_cached, cached, sync_cached
|
|
2
|
+
from ._backend._exceptions import CachifyInitError, CachifyLockError
|
|
3
|
+
from ._backend._lib import init_cachify
|
|
4
|
+
from ._backend._lock import async_once, lock, once, sync_once
|
|
5
|
+
from ._backend._types._common import AsyncClient, Decoder, Encoder, SyncClient
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from importlib.metadata import version
|
|
10
|
+
|
|
11
|
+
__version__ = version('py-cachify')
|
|
12
|
+
except ModuleNotFoundError:
|
|
13
|
+
__version__ = f'No version available for {__name__}'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
'CachifyInitError',
|
|
18
|
+
'CachifyLockError',
|
|
19
|
+
'init_cachify',
|
|
20
|
+
'lock',
|
|
21
|
+
'Encoder',
|
|
22
|
+
'Decoder',
|
|
23
|
+
'cached',
|
|
24
|
+
'once',
|
|
25
|
+
'AsyncClient',
|
|
26
|
+
'SyncClient',
|
|
27
|
+
# The following are deprecated (and are just aliases)
|
|
28
|
+
'async_once',
|
|
29
|
+
'sync_once',
|
|
30
|
+
'async_cached',
|
|
31
|
+
'sync_cached',
|
|
32
|
+
]
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from functools import partial, wraps
|
|
3
|
+
from typing import Awaitable, Callable, Tuple, TypeVar, Union, cast, overload
|
|
4
|
+
|
|
5
|
+
from typing_extensions import ParamSpec, deprecated
|
|
6
|
+
|
|
7
|
+
from ._helpers import a_reset, encode_decode_value, get_full_key_from_signature, is_coroutine, reset
|
|
8
|
+
from ._lib import get_cachify
|
|
9
|
+
from ._types._common import Decoder, Encoder
|
|
10
|
+
from ._types._reset_wrap import AsyncResetWrappedF, SyncResetWrappedF, WrappedFunctionReset
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_R = TypeVar('_R')
|
|
14
|
+
_P = ParamSpec('_P')
|
|
15
|
+
_S = TypeVar('_S')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def cached(
|
|
19
|
+
key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
|
|
20
|
+
) -> WrappedFunctionReset:
|
|
21
|
+
"""
|
|
22
|
+
Decorator that caches the result of a function based on the specified key, time-to-live (ttl),
|
|
23
|
+
and encoding/decoding functions.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
key (str): The key used to identify the cached result, could be a format string.
|
|
27
|
+
ttl (Union[int, None], optional): The time-to-live for the cached result.
|
|
28
|
+
Defaults to None, means indefinitely.
|
|
29
|
+
enc_dec (Union[Tuple[Encoder, Decoder], None], optional): The encoding and decoding functions for the cached value.
|
|
30
|
+
Defaults to None.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
WrappedFunctionReset: Either a synchronous or asynchronous function with reset method attached to it,
|
|
34
|
+
reset(*args, **kwargs) matches the type of original function, accepts the same argument,
|
|
35
|
+
and could be used to reset the cache.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
@overload
|
|
39
|
+
def _cached_inner( # type: ignore[overload-overlap]
|
|
40
|
+
_func: Callable[_P, Awaitable[_R]],
|
|
41
|
+
) -> AsyncResetWrappedF[_P, _R]: ...
|
|
42
|
+
|
|
43
|
+
@overload
|
|
44
|
+
def _cached_inner(
|
|
45
|
+
_func: Callable[_P, _R],
|
|
46
|
+
) -> SyncResetWrappedF[_P, _R]: ...
|
|
47
|
+
|
|
48
|
+
def _cached_inner(
|
|
49
|
+
_func: Union[Callable[_P, _R], Callable[_P, Awaitable[_R]]],
|
|
50
|
+
) -> Union[AsyncResetWrappedF[_P, _R], SyncResetWrappedF[_P, _R]]:
|
|
51
|
+
signature = inspect.signature(_func)
|
|
52
|
+
|
|
53
|
+
enc, dec = None, None
|
|
54
|
+
if enc_dec is not None:
|
|
55
|
+
enc, dec = enc_dec
|
|
56
|
+
|
|
57
|
+
if is_coroutine(_func):
|
|
58
|
+
_awaitable_func = _func
|
|
59
|
+
|
|
60
|
+
@wraps(_awaitable_func)
|
|
61
|
+
async def _async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
62
|
+
cachify = get_cachify()
|
|
63
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
64
|
+
if val := await cachify.a_get(key=_key):
|
|
65
|
+
return cast(_R, encode_decode_value(encoder_decoder=dec, val=val))
|
|
66
|
+
|
|
67
|
+
res = await _awaitable_func(*args, **kwargs)
|
|
68
|
+
await cachify.a_set(key=_key, val=encode_decode_value(encoder_decoder=enc, val=res), ttl=ttl)
|
|
69
|
+
return res
|
|
70
|
+
|
|
71
|
+
setattr(_async_wrapper, 'reset', partial(a_reset, signature=signature, key=key))
|
|
72
|
+
|
|
73
|
+
return cast(AsyncResetWrappedF[_P, _R], cast(object, _async_wrapper))
|
|
74
|
+
else:
|
|
75
|
+
|
|
76
|
+
@wraps(_func) # type: ignore[unreachable]
|
|
77
|
+
def _sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
78
|
+
cachify = get_cachify()
|
|
79
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
80
|
+
if val := cachify.get(key=_key):
|
|
81
|
+
return encode_decode_value(encoder_decoder=dec, val=val)
|
|
82
|
+
|
|
83
|
+
res = _func(*args, **kwargs)
|
|
84
|
+
cachify.set(key=_key, val=encode_decode_value(encoder_decoder=enc, val=res), ttl=ttl)
|
|
85
|
+
return cast(_R, res)
|
|
86
|
+
|
|
87
|
+
setattr(_sync_wrapper, 'reset', partial(reset, signature=signature, key=key))
|
|
88
|
+
|
|
89
|
+
return cast(SyncResetWrappedF[_P, _R], cast(object, _sync_wrapper))
|
|
90
|
+
|
|
91
|
+
return cast(WrappedFunctionReset, cast(object, _cached_inner))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@deprecated('sync_cached is deprecated, use cached instead. Scheduled for removal in 3.0.0')
|
|
95
|
+
def sync_cached(
|
|
96
|
+
key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
|
|
97
|
+
) -> WrappedFunctionReset:
|
|
98
|
+
return cached(key=key, ttl=ttl, enc_dec=enc_dec)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@deprecated('async_cached is deprecated, use cached instead. Scheduled for removal in 3.0.0')
|
|
102
|
+
def async_cached(
|
|
103
|
+
key: str, ttl: Union[int, None] = None, enc_dec: Union[Tuple[Encoder, Decoder], None] = None
|
|
104
|
+
) -> WrappedFunctionReset:
|
|
105
|
+
return cached(key=key, ttl=ttl, enc_dec=enc_dec)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
from typing import Any, Awaitable, Callable, TypeVar, Union
|
|
4
|
+
|
|
5
|
+
from typing_extensions import ParamSpec, TypeIs
|
|
6
|
+
|
|
7
|
+
from ._lib import get_cachify
|
|
8
|
+
from ._types._common import Decoder, Encoder
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_R = TypeVar('_R', covariant=True)
|
|
12
|
+
_P = ParamSpec('_P')
|
|
13
|
+
_S = TypeVar('_S')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_full_key_from_signature(bound_args: inspect.BoundArguments, key: str) -> str:
|
|
17
|
+
args_dict = bound_args.arguments
|
|
18
|
+
args = args_dict.pop('args', ())
|
|
19
|
+
kwargs = args_dict.pop('kwargs', {})
|
|
20
|
+
kwargs.update(args_dict)
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
return key.format(*args, **kwargs)
|
|
24
|
+
except IndexError:
|
|
25
|
+
raise ValueError('Arguments in a key do not match function signature') from None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_coroutine(
|
|
29
|
+
func: Union[Callable[_P, Awaitable[_R]], Callable[_P, _R]],
|
|
30
|
+
) -> TypeIs[Callable[_P, Awaitable[_R]]]:
|
|
31
|
+
return asyncio.iscoroutinefunction(func)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def encode_decode_value(encoder_decoder: Union[Encoder, Decoder, None], val: Any) -> Any:
|
|
35
|
+
if not encoder_decoder:
|
|
36
|
+
return val
|
|
37
|
+
|
|
38
|
+
return encoder_decoder(val)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def reset(*args: Any, key: str, signature: inspect.Signature, **kwargs: Any) -> None:
|
|
42
|
+
cachify = get_cachify()
|
|
43
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
44
|
+
|
|
45
|
+
cachify.delete(key=_key)
|
|
46
|
+
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def a_reset(*args: Any, key: str, signature: inspect.Signature, **kwargs: Any) -> None:
|
|
51
|
+
cachify = get_cachify()
|
|
52
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
53
|
+
|
|
54
|
+
await cachify.a_delete(key=_key)
|
|
55
|
+
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def is_alocked(*args: Any, key: str, signature: inspect.Signature, **kwargs: Any) -> bool:
|
|
60
|
+
cachify = get_cachify()
|
|
61
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
62
|
+
|
|
63
|
+
return bool(await cachify.a_get(key=_key))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_locked(*args: Any, key: str, signature: inspect.Signature, **kwargs: Any) -> bool:
|
|
67
|
+
cachify = get_cachify()
|
|
68
|
+
_key = get_full_key_from_signature(bound_args=signature.bind(*args, **kwargs), key=key)
|
|
69
|
+
|
|
70
|
+
return bool(cachify.get(key=_key))
|
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
1
|
import pickle
|
|
4
|
-
from typing import Any, Union
|
|
2
|
+
from typing import Any, Optional, Union
|
|
5
3
|
|
|
6
|
-
from
|
|
7
|
-
from
|
|
8
|
-
from
|
|
4
|
+
from ._clients import AsyncWrapper, MemoryCache
|
|
5
|
+
from ._exceptions import CachifyInitError
|
|
6
|
+
from ._types._common import AsyncClient, SyncClient
|
|
9
7
|
|
|
10
8
|
|
|
11
9
|
class Cachify:
|
|
@@ -13,14 +11,16 @@ class Cachify:
|
|
|
13
11
|
self,
|
|
14
12
|
sync_client: Union[SyncClient, MemoryCache],
|
|
15
13
|
async_client: Union[AsyncClient, AsyncWrapper],
|
|
14
|
+
default_expiration: Optional[int],
|
|
16
15
|
prefix: str,
|
|
17
16
|
) -> None:
|
|
18
17
|
self._sync_client = sync_client
|
|
19
18
|
self._async_client = async_client
|
|
20
19
|
self._prefix = prefix
|
|
20
|
+
self.default_expiration = default_expiration
|
|
21
21
|
|
|
22
22
|
def set(self, key: str, val: Any, ttl: Union[int, None] = None) -> Any:
|
|
23
|
-
self._sync_client.set(name=f'{self._prefix}{key}', value=pickle.dumps(val), ex=ttl)
|
|
23
|
+
_ = self._sync_client.set(name=f'{self._prefix}{key}', value=pickle.dumps(val), ex=ttl)
|
|
24
24
|
|
|
25
25
|
def get(self, key: str) -> Any:
|
|
26
26
|
return (val := self._sync_client.get(name=f'{self._prefix}{key}')) and pickle.loads(val)
|
|
@@ -38,16 +38,34 @@ class Cachify:
|
|
|
38
38
|
return await self._async_client.delete(f'{self._prefix}{key}')
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
_cachify: Cachify
|
|
41
|
+
_cachify: Optional[Cachify] = None
|
|
42
|
+
_mc = MemoryCache()
|
|
43
|
+
_amc = AsyncWrapper(_mc)
|
|
42
44
|
|
|
43
45
|
|
|
44
46
|
def init_cachify(
|
|
45
|
-
sync_client: SyncClient =
|
|
46
|
-
async_client: AsyncClient =
|
|
47
|
-
|
|
47
|
+
sync_client: SyncClient = _mc,
|
|
48
|
+
async_client: AsyncClient = _amc,
|
|
49
|
+
default_lock_expiration: Optional[int] = 30,
|
|
50
|
+
prefix: str = 'PYC-',
|
|
48
51
|
) -> None:
|
|
52
|
+
"""
|
|
53
|
+
Initialize the Cachify instance with the specified clients and settings.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
sync_client (Union[SyncClient, MemoryCache], optional): The synchronous client to use.
|
|
57
|
+
Defaults to MemoryCache().
|
|
58
|
+
async_client (Union[AsyncClient, AsyncWrapper], optional): The asynchronous client to use.
|
|
59
|
+
Defaults to AsyncWrapper(cache=MemoryCache()).
|
|
60
|
+
default_lock_expiration (Optional[int], optional): The default expiration time for locks.
|
|
61
|
+
Defaults to 30.
|
|
62
|
+
prefix (str, optional): The prefix to use for keys. Defaults to 'PYC-'.
|
|
63
|
+
"""
|
|
64
|
+
|
|
49
65
|
global _cachify
|
|
50
|
-
_cachify = Cachify(
|
|
66
|
+
_cachify = Cachify(
|
|
67
|
+
sync_client=sync_client, async_client=async_client, prefix=prefix, default_expiration=default_lock_expiration
|
|
68
|
+
)
|
|
51
69
|
|
|
52
70
|
|
|
53
71
|
def get_cachify() -> Cachify:
|