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:

  • rpush: Allows you to insert elements at the end of the list
  • llenReturns the list's length
  • lindex: Returns the element passing a specific index as a parameter, where the first element is index 0
  • lrange: Returns elements from a list, passing the name of the list and indexes for the start and end elements as parameters:
>>> 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset