Build your first Redis Hello World application in Python

Learn how to connect to the Redis data structure store with "Hello World."
355 readers like this.
Beginners to Open Source theme: Hello World on bread

Photo by Windell Oskay, modified by Jen Wike Huger

Hello World is a simple way to start exploring a new programming language, and it's almost always the first program people create. If you're reading this, you're probably new to Redis or Python and want to learn. To help you do that, let's build a "Hello Redis" program.

Redis

Redis, which stands for REmote DIctionary Server, is a BSD-licensed, in-memory data structure store released in 2009 by Salvatore Sanfilippo. One of the big differences between Redis and other NoSQL databases is the data structures that Redis provides. Instead of working with a table abstraction, Redis developers can leverage data structures like strings, hashes, lists, sets, and sorted sets using commands similar to the collection operations in most programming languages. Redis has replication capabilities, a server-side scripting language (Lua), transactions, and different modes of disk persistence.

Unless you've installed Redis for another project, more than likely it's not bundled with your operating system distribution. Using your OS package manager or third-party port system, you can download and install Redis on Linux and MacOS systems. Most packages will install a basic Redis configuration that starts up listening on port 6379, the default port for Redis.

Python

Python is an interpreted, high-level programming language created by Guido van Rossum. It was released in 1991 under the Python Software Foundation License. The foundation oversees the development of Python, with Guido serving as the project's Benevolent Dictator for Life (BDFL). Python was designed to be approachable, with a simple syntax and an emphasis on readability. Its notable feature is that the indenting level of the code is used to indicate block structure.

Most Linux distributions and MacOS install Python by default, so it's likely you already have an appropriate version. The current version is Python 3, so the code in this article is written to run under it, but many operating systems install Python 2, and our code will work with Python 2.7.

You will need to install the redis-py package to connect to Redis, and you can do so using pip or pip3 (the Python package manager) with the following command:

pip3 install redis

If you see a message similar to Requirement already satisfied: Redis, the Redis-py package is already installed on your system.

Hello Redis

Our Hello Redis program uploads a "hello" message to the Redis server, downloads the message that was just uploaded, and displays it to the user. Writing this program in Python (as in most languages) takes five basic steps:

  1. Import the Redis library
  2. Define connection parameters
  3. Instantiate the Redis connection object
  4. Upload a message to Redis using the connection object
  5. Download the message from Redis using the connection object

Each step is implemented in the script below:

#!/usr/bin/env python3

# step 1: import the redis-py client package
import redis

# step 2: define our connection information for Redis
# Replaces with your configuration information
redis_host = "localhost"
redis_port = 6379
redis_password = ""


def hello_redis():
    """Example Hello Redis Program"""
    
    # step 3: create the Redis Connection object
    try:
    
        # The decode_repsonses flag here directs the client to convert the responses from Redis into Python strings
        # using the default encoding utf-8.  This is client specific.
        r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)
    
        # step 4: Set the hello message in Redis 
        r.set("msg:hello", "Hello Redis!!!")

        # step 5: Retrieve the hello message from Redis
        msg = r.get("msg:hello")
        print(msg)        
    
    except Exception as e:
        print(e)


if __name__ == '__main__':
    hello_redis()

Once you copy the code into a file and change the connection parameters in step 2 to connect to your own Redis instance, you can run this script directly from a Unix shell. If your connection parameters are specified correctly, you will see the message Hello Redis!!!.

Once you're comfortable with this code, modify it to use the set and get methods to upload different data. From there, you can experiment with some of the other Redis data types linked above.

User profile image.
A self-professed database geek who runs the developer relations program for Redis Labs. At Redis Labs he focuses on supporting and growing the Redis developer community through community meetups, technical training, and developer evangelism.

1 Comment

I am so surprised the redis library for python isn't using these defaults as fallbacks to environment variables if None is received for host, port, password (allowing for override, but also avoiding cluttering code) https://github.com/andymccurdy/redis-py/issues/970

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.