Using Predix Cache with Python

Get code samples and recommended libraries for using a Predix-Redis service with Python.

Code Samples for Using Predix Cache with Python

Recommended Libraries
redis-py. See https://github.com/andymccurdy/redis-py
Alternative Libraries
None.

Code Samples Using redis-py Library

To include the redis-py module, create a requirements.txt file and add the following line:
redis
Sample Cloud Foundry manifest
applications:
- name: redis-single-sample
  mem: 256M
  disk: 1024M
  instances: 1
  command: python redis-single-sample.py
  services:
    - redis-shared-sample
redis-py Sample for Shared and Dedicated Single Node Service Plans
import redis
import json
import os

if 'VCAP_SERVICES' in os.environ:
    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
    redis_info = vcap_services['predix-redis'][0]
    credentials = redis_info['credentials']
try:
    conn = redis.StrictRedis(
        host = credentials['host'],
        port = credentials['port'],
        password = credentials['password'])
    print conn
    conn.set('foo', 'bar')
    print 'Get Record Foo:', conn.get('foo')
except Exception as ex:
    print 'Error:', ex

redis-py Sample for High Availability Service Plans using Sentinels

import redis
import json
import os
from redis.sentinel import Sentinel

if 'VCAP_SERVICES' in os.environ:
    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
    redis_info = vcap_services['predix-redis'][0]
    credentials = redis_info['credentials']
try:
    sentinel = Sentinel([
        (credentials['ip_list'][0], credentials['sentinel_port']),
        (credentials['ip_list'][1], credentials['sentinel_port']),
        (credentials['ip_list'][2], credentials['sentinel_port'])
    ], password = credentials['password'], socket_timeout=0.1)

    print 'Master is: ', sentinel.discover_master(credentials['master_name'])
    print 'Slaves are: ', sentinel.discover_slaves(credentials['master_name'])

    master = sentinel.master_for(credentials['master_name'], socket_timeout=0.1)
    master.set('foo', 'bar')
    print 'Get Record Foo:', master.get('foo')
except Exception as ex:
    print 'Error:', ex

Validate Connectivity

To verify the application is able to connect, look at the log output by using the following command:
cf logs sample-name --recent
Output example for single node service plans:
[App/0] OUT StrictRedis<ConnectionPool<Connection<host=10.72.27.128,port=6043,db=0>>>
[App/0] OUT Get Record Foo: bar
Output example for high availability service plans using Sentinels:
[App/0] OUT Master is:  ('10.72.8.161', 6379)
[App/0] OUT Slaves are:  [('10.72.9.249', 6379), ('10.72.8.162', 6379)]
[App/0] OUT Get Record Foo: bar

See redis-py Sentinel for more Sentinel documentation.