Using Redis with Python

We will need Python bindings for Redis. Install redis-py via pip using the following command:

pip install redis==2.10.6

You can find the redis-py docs at https://redis-py.readthedocs.io/.

The redis-py package offers two classes for interacting with Redis: StrictRedis and Redis. Both offer the same functionality. The StrictRedis class attempts to adhere to the official Redis command syntax. The Redis class extends StrictRedis, overriding some methods to provide backward compatibility. We will use StrictRedis since it follows the Redis command syntax. Open the Python shell and execute the following code:

>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)

The preceding code creates a connection with the Redis database. In Redis, databases are identified by an integer index instead of a database name. By default, a client is connected to the database 0. The number of available Redis databases is set to 16, but you can change this in the redis.conf configuration file.

Now, set a key using the Python shell:

>>> r.set('foo', 'bar')
True

The command returns True, indicating that the key has been successfully created. Now, you can retrieve the key using the get() command:

>>> r.get('foo')
b'bar'

As you can note from the preceding code, the methods of StrictRedis follow the Redis command syntax.

Let's integrate Redis into our project. Edit the settings.py file of the bookmarks project and add the following settings to it:

REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0

These are the settings for the Redis server and the database that we will use for our project.

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

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