AWS ElastiCache with Redis Part – 2 (Flask application)
- In our previous part, we have covered the basics of caching and ElastiCache. link- https://statusneo.com/aws-elasticache-with-redis-part-1/
- In this part, we will cover how to implement Redis in our Flask App.
- Just for convenience, we will host the Redis server on our local system, so that it can become on how to use Redis.
- For using ElastiCache we can simply log in to AWS ElastiCache and host a Redis server there.
- we can download Redis for here- https://redis.io/downloadhttps://redis.io/download
- Then we can open Redis in any editor say visual studio, it will look something like this-
- Now we will go to the src folder and run ./redis-server it will start the Redis server locally.
Implementing Caching on Flask Application
- Let’s create a small flask application, that hits an opensource API that fetches the covid data.
- The structure of our application looks like this-
- Let’s see the time taken by the API to fetch the data without caching.
- we can see that it’s around 845ms.
- Let’s now try to implement caching in it using the Redis server and flask caching.
- we will create a config file in our project source directory having the Redis database configuration.
- Now in our main file, we are going to add this configuration to our app and app caching to our API’s.
- timeout is in seconds that means how much time the data will be retained in our cache.
- Let us know try to hit the API with the latest changes.
- Now you can see that after the data has been cached after the first hit, it is taking only 10ms that is almost 83% less then its original time.
- This is how cache is implemented in flask application using Redis database.
- First Part – https://statusneo.com/aws-elasticache-with-redis-part-1/
- Utkarsh Shukla Website – https://utkarshshukla.herokuapp.com/