Redis is one of the most popular open-source, in-memory data stores because of its versatility in caching, session storage, real-time data storage, messaging, and high-speed data ingestion. It might just be the silver bullet that your app needs.
In this post, we will have a look at how to use Python to cache data on a Redis server.
Why Redis?
The versatility of Redis allows it to act as a database, cache, message broker, and streaming engine. Also, due to the performance-oriented nature of Redis, it's ideal for creating high-performance applications. Moreover, Redis has features such as clustering, high availability, server-side scripting via Lua, and server-side stored procedures via Redis functions and extensibility, which makes Redis suitable for handling most user requirements.
Caching Data with Redis
As an in-memory key-value store, Redis is tailor-made for caching data. In a typical setting, Redis will sit in between a more traditional database like MySQL or PostgreSQL and a software application and provide a high-speed storage layer for frequently accessed data. Thus allowing the software application to quickly access this data without having to query the database every time an end-user makes a request.
As this is the most prominent use case for Redis, let us look at how we can utilize Redis in a Python application to cache data.
Project Setup
Before starting caching, this tutorial assumes that you already have a Redis instance up and running in your environment. If not, follow this tutorial by Redis to install Redis in your environment.
For the weather data, we will be using the API provided by www.weatherapi.com.
First let’s setup a pip environment and install our necessary packages:
pipenv -python 3.8
pipenv install redis requests
The requests package will be used to interact with the API, while the Redis package is used to connect with the Redis server.
Creating the Application
Next up is to create the application. The following code block demonstrates a simple application that retrieves weather info for a given city via the API or Redis Cache.
As you can see from the above result, When the program is executed for the first time, it will query the data via the API as there is no matching key available in the cache. The data obtained then will be cached to Redis with the city as the key and response content as the value. Any subsequent executions of the program specifying the same city will fetch the data from Redis without hitting the API until the cache expires after 3600 seconds. Then the program will query the API again and cache an updated set of data for the given city.
That’s how simple it is to start using Redis. What are you going to use Redis for? Let us know down below!
Happy coding from your friends at Codesphere, the all-in-one development platform!
Top comments (0)