|
1 | 1 | # Redis cache for Python |
2 | 2 |
|
3 | | -- Simple python redis cache library, mostly used as distributed caching, where application servers is in separated processes such as Gunicorn workers, K8s replicas. |
| 3 | +- Simple python redis cache library, mostly used as [distributed caching](https://redis.com/glossary/distributed-caching), where application servers is in separated processes such as Gunicorn workers, K8s replicas, .etc.. |
4 | 4 | - **Asyncio Support for FastAPI, Starlette** |
5 | 5 |
|
6 | 6 | ## Requirements |
@@ -45,4 +45,53 @@ print(result) |
45 | 45 | # [4, 10, 18] |
46 | 46 | ``` |
47 | 47 |
|
| 48 | +**Asynchronous with asyncio** |
| 49 | + |
| 50 | +```python |
| 51 | +import asyncio |
| 52 | +from py_redis_cache.asyncio import AsyncRedisCache |
| 53 | + |
| 54 | +# init redis_cache instance and connection |
| 55 | +redis_cache = AsyncRedisCache( |
| 56 | + host="127.0.0.1", |
| 57 | + port=6379, |
| 58 | + verbose=1 # Turn on logging for demonstration, set to 0 for silent caching |
| 59 | +) |
| 60 | + |
| 61 | +@redis_cache.aio_cache(ttl=10) # Expire after 10 seconds |
| 62 | +async def heavy_compute(a: list, b: list): |
| 63 | + length = max(len(a), len(b)) |
| 64 | + c = [[]] * length |
| 65 | + for i in range(length): |
| 66 | + c[i] = a[i] * b[i] |
| 67 | + return c |
| 68 | + |
| 69 | +async def test_async_cache(): |
| 70 | + result = await heavy_compute([1, 2, 3], [4, 5, 6]) |
| 71 | + print(result) |
| 72 | + |
| 73 | + # Now the result is cached |
| 74 | + result2 = await heavy_compute([1, 2, 3], [4, 5, 6]) |
| 75 | + |
| 76 | + print(result2) |
| 77 | + |
| 78 | +loop = asyncio.get_event_loop() |
| 79 | +loop.run_until_complete(test_async_cache()) |
| 80 | + |
| 81 | +# Cache added, key=redis_cache::11=__main__.heavy_compute(a=[1, 2, 3].b=[4, 5, 6]), size=0.000Kb |
| 82 | +# [4, 10, 18] |
| 83 | +# Cache hit, key=redis_cache::11=__main__.heavy_compute(a=[1, 2, 3].b=[4, 5, 6]) |
| 84 | +# [4, 10, 18] |
| 85 | +``` |
| 86 | + |
| 87 | +## Advanced usage |
| 88 | + |
48 | 89 | for further examples and use cases please visit [examples](examples) |
| 90 | + |
| 91 | +## Testing |
| 92 | + |
| 93 | +**NOTE**: Please make sure you have redis running on `127.0.0.1:6379` to run test. |
| 94 | + |
| 95 | +```bash |
| 96 | +$ python3 -m unittest discover tests |
| 97 | +``` |
0 commit comments