This is an example of a FastAPI application integrated with asyncio Redis using the FastAPI lifespan feature. The application demonstrates how to connect to a Redis database asynchronously during the lifespan of the FastAPI application and perform CRUD operations.
- launch coroutine redis with threading
- alternative depreciated fastapi on_start event
- https://fastapi.tiangolo.com/advanced/events/
- https://stackoverflow.com/questions/76322463/how-to-initialise-a-global-object-or-variable-and-reuse-it-in-every-fastapi-endp
python fastapi-redis.py
- get
- post
The Redis class provides methods to connect to Redis, insert a string value, and query a key from Redis. These methods use the redis.asyncio library for asynchronous Redis operations.
The run_redis coroutine function connects to Redis, inserts a string value ('fastapi') with the key 'stackoverflow', queries the value from Redis, and returns the Redis instance.
The lifespan async context manager initializes the Redis connection during the startup of the FastAPI application and cleans up the connection during shutdown. It stores the Redis instance in the FastAPI app state for easy access by request handlers.
Two endpoints are defined: /redis for retrieving the value of the 'stackoverflow' key and /redis POST method for inserting a new value for the 'stackoverflow' key. These endpoints use the Redis instance stored in the app state to interact with Redis.
To run the application, execute the main module using Uvicorn with the specified host and port. The FastAPI application will be served with asynchronous Redis integration enabled.