Python Connection Examples

The redis-py package is the recommended client for Redis when using Python.

Installation

Install redis-py at the command prompt if you haven’t yet:

$ pip install redis

Connecting with SSL

Connecting to your instance via SSL requires using a certificate authority. See documentation for certificates and fingerprints for more details.

import redis

try:
    conn = redis.StrictRedis(
        host='#####.publb.rackspaceclouddb.com',
        port=6380,
        password='YOUR_PASSWORD',
        ssl=True,
        ssl_ca_certs='LOCAL/PATH/TO/rackspace-ca-2016.pem')
    print conn
    conn.ping()
    print 'Connected!'
except Exception as ex:
    print 'Error:', ex
    exit('Failed to connect, terminating.')

Connecting without SSL

import redis

try:
    conn = redis.StrictRedis(
        host='#####.publb.rackspaceclouddb.com',
        port=6379,
        password='YOUR_PASSWORD')
    print conn
    conn.ping()
    print 'Connected!'
except Exception as ex:
    print 'Error:', ex
    exit('Failed to connect, terminating.')

Creating, Reading, Updating and Deleting Records

import redis

try:
    conn = redis.StrictRedis(
        host='#####.publb.rackspaceclouddb.com',
        port=6380,
        password='YOUR_PASSWORD',
        ssl=True,
        ssl_ca_certs='LOCAL/PATH/TO/rackspace-ca-2016.pem')
    print 'Set Record:', conn.set("best_car_ever", "Tesla Model S")
    print 'Get Record:', conn.get("best_car_ever")
    print 'Delete Record:', conn.delete("best_car_ever")
    print 'Get Deleted Record:', conn.get("best_car_ever")
except Exception as ex:
    print 'Error:', ex

Output from above:

Set Record: True
Get Record: Tesla Model S
Delete Record: 1
Get Deleted Record: None

Note

‘del’ is a reserved keyword in the Python syntax. Therefore redis-py uses ‘delete’ instead.

More Information

If you need additional help with redis-py, here are some useful links:

As always, if you have any questions, please don’t hesitate to reach out to our support team!