I'm new to Redis, and I want to use aioredis
in fastapi
(write data to redis then get data)
The code and error result is following:
code
import asyncio
from redis import asyncio as aioredis
from fastapi import FastAPI
import uvicorn
app = FastAPI()
HOST = "0.0.0.0"
REDIS_PORT = 6379
@app.on_event('startup')
async def register_redis():
app.state.redis = await aioredis.from_url(
f'redis://{HOST}',
port=REDIS_PORT,
encoding='utf-8'
)
print('INFO: Resister redis successfully')
@app.get("/read-from-redis/{key}")
async def read_from_redis(key: str) -> dict:
value = await app.state.redis.get(key)
if value is not None:
return {"key": key, "value": value}
else:
return {"message": "Key not found in Redis"}
async def write_to_redis(key: str, value: str) -> dict:
await app.state.redis.set(key, value)
return {"message": f"Value '{value}' written to Redis with key '{key}'"}
asyncio.run(write_to_redis(1, 10))
if __name__ == "__main__":
uvicorn.run(app="io_redis:app", host=HOST, port=8000, reload=True)
Result
INFO: Started server process [3888]
INFO: Waiting for application startup.
INFO: Resister redis successfully
INFO: Application startup complete.
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\starlette\datastructures.py", line 695, in __getattr__
return self._state[key]
KeyError: 'redis'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\io_redis.py", line 44, in <module>
await app.state.redis.set(key, value)
File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\starlette\datastructures.py", line 698, in __getattr__
raise AttributeError(message.format(self.__class__.__name__, key))
AttributeError: 'State' object has no attribute 'redis'
register_redis()
will setup app.state.redis
when application startup.
Why the app.state
cannot get redis
when call write_to_redis()
?