Introduction to Redis

Basically, Redis is a tool for data structures in memory and is used as a database cache. With it, most of the data is in memory, making the request for information that's required through queries much faster.

We can create a connection to Redis from Python by using the redis-py package, where port=6379 and db=0 are default values:

>>> import redis
>>> redis_client = redis.Redis(host='localhost', port=6379, db=0)
>>> print(redis_client)
Redis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>

Now that we are connected to Redis, we can start reading and writing data. The following instruction writes the my_value to the Redis my_key key, reads it back, and prints it:

>>> redis_client.set('my_key','my_value')
True
>>> redis_client.get('my_key')
b'my_value'

With Redis, we can also manage lists in an easy way. These are the methods we can use for managing this list:

>>> redis_client.rpush('my_list', 'http')
1
>>> redis_client.rpush('my_list', 'ftp')
2
>>> redis_client.rpush('my_list', 'smtp')
3
>>> redis_client.rpush('my_list', 'tcp')
4
>>> redis_client.rpush('my_list', 'udp')
5
>>> redis_client.llen('my_list')
5
>>> redis_client.lindex('my_list',2)
B'smtp'

>>> redis_client.lrange('my_list',0,4)
[b'http', b'ftp', b'smtp', b'tcp', b'udp']

In the previous script execution, we can see how we can add elements in the redis_client list, get the list's length, get an element from a specific index, and get elements from the start and end indexes of the list.