Connect to Redis with Python

Python clients you can use to connect to a Redis Server are listed in the documentation. I personally use redis-py, but Redis the company has just released Redis OM for Python, so I think it is worth to have a look. I will share here basic instructions to connect to a Redis Server and test a couple of commands.

Connect using redis-py

In the first place, when working with Python, I would recommend to setup a virtual environment (venv), so to isolate the Python environment under testing from the global environment. You can create the venv as follows.

python3 -m venv redisvenv
source redisvenv/bin/activate
pip install redis

Now that the venv is ready to use, let’s try a simple hello world script.

#!/usr/bin/python3
import redis

r = redis.Redis(host='127.0.0.1', port=4321, password='')
r.set('hello', 'world')
print (r.get('hello'))
r.delete('hello')

Executing this basic script will return the value attributed to the key hello and clean up the key/value pair.

(redisvenv) bash-3.2$ python test.py 
b'world'

Note that the ‘b’ means that the result is returned as a byte string. You can convert to utf-8 by connecting as follows:

r = redis.StrictRedis(host='127.0.0.1', port=4321, charset="utf-8", decode_responses=True)

And get the result:

(redisvenv) bash-3.2$ python test.py 
world

Consult redis-py documentation and refer also to Redis Enterprise documentation for additional insights about using Python to connect to Redis.

Connect using Redis OM

Using redis-py or any other similar connector, you will have access to well known data structures and the usual commands. But for advanced users, Redis OM for Python is the deus ex machina which boosts expressiveness of the code, and therefore unleash the whole potential of data modelling using Redis. Presented in December 2021, Redis OM is a brand new library that enables developers to use object mapping, data validation, indexes, nested data structures using JSON and the ability to interact with all these features in a compact way, from the same library and, above all, without compromising on the performance you are used to. Redis OM libraries are installed simply using (I will install the mail validator I am about to use in an example):

pip install redis-om
pip install pydantic[email]

Now configure the environment variable to instruct Redis OM to connect to the Server:

export REDIS_OM_URL=redis://@127.0.0.1:4321

And finally check one of the examples from the docs:

import datetime
from typing import Optional
from pydantic import EmailStr
from redis_om import HashModel

class Customer(HashModel):
    first_name: str
    last_name: str
    email: EmailStr
    join_date: datetime.date
    age: int
    bio: Optional[str]

# First, we create a new `Customer` object:
andrew = Customer(
    first_name="Andrew",
    last_name="Brookins",
    email="andrew.brookins@example.com",
    join_date=datetime.date.today(),
    age=38,
    bio="Python developer, works at Redis, Inc."
)

# The model generates a globally unique primary key automatically
# without needing to talk to Redis.
print(andrew.pk)

# We can save the model to Redis by calling `save()`:
andrew.save()
andrew.key()

Consult the Redis OM introduction in this post and check for examples here. I am sure you’ll have a lot of fun using Redis OM!

Redis is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Any use by mortensi is for referential purposes only and does not indicate any sponsorship, endorsement or affiliation between Redis and mortensi.

Leave A Comment