Created
July 24, 2022 08:09
-
-
Save charsyam/1efc7f38860225c63b05379fffe73256 to your computer and use it in GitHub Desktop.
FastAPI + aioredis simple settings
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 | |
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