Skip to content

Instantly share code, notes, and snippets.

@charsyam
Created July 24, 2022 08:09
Show Gist options
  • Save charsyam/1efc7f38860225c63b05379fffe73256 to your computer and use it in GitHub Desktop.
Save charsyam/1efc7f38860225c63b05379fffe73256 to your computer and use it in GitHub Desktop.
FastAPI + aioredis simple settings
from fastapi import FastAPI
import aioredis
app = FastAPI()
async def redis_pool():
# Redis client bound to pool of connections (auto-reconnecting).
return aioredis.from_url(
"redis://localhost", encoding="utf-8", decode_responses=True
)
@app.on_event("startup")
async def create_redis():
app.state.redis = await redis_pool()
@app.on_event("shutdown")
async def close_redis():
await app.state.redis.close()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def say_hello(name: str):
redis_client = app.state.redis
keys = await redis_client.get(name)
return {"message": f"Hello {keys}"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment