Created
May 30, 2021 20:01
-
-
Save goltsevnet/5311bdd7ab96ffcf0a5ea3d7a392592d to your computer and use it in GitHub Desktop.
aredis manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
from aioredis import Redis, create_redis_pool | |
class RedisCache: | |
def __init__(self): | |
self.redis_cache: Optional[Redis] = None | |
async def init_cache(self): | |
self.redis_cache = await create_redis_pool("redis://localhost:6379/0?encoding=utf-8") | |
async def keys(self, pattern): | |
return await self.redis_cache.keys(pattern) | |
async def set(self, key, value): | |
return await self.redis_cache.set(key, value) | |
async def get(self, key): | |
return await self.redis_cache.get(key) | |
async def close(self): | |
self.redis_cache.close() | |
await self.redis_cache.wait_closed() | |
redis_cache = RedisCache() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI | |
from uvicorn import run | |
from connections import redis_cache | |
app = FastAPI() | |
async def get_all(): | |
return await redis_cache.keys('*') | |
@app.on_event('startup') | |
async def starup_event(): | |
await redis_cache.init_cache() | |
@app.on_event('shutdown') | |
async def shutdown_event(): | |
redis_cache.close() | |
await redis_cache.wait_closed() | |
@app.get('/') | |
async def redis_keys(): | |
return await get_all() | |
if __name__ == '__main__': | |
run("main:app", port=3000, reload=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment