Connecting to Azure Redis Cache Service from Python

Recently I had someone ask me how to connect to the Microsoft Azure Redis Cache Service from Python. I figured it would be easy considering how simple python is to learn. It turned out to be a little trickier than expected but still not too hard nonetheless.

Below is the sample code, then I’ll explain what each part is doing.

import redis
 
r = redis.StrictRedis(host='[cache-name].redis.cache.windows.net', port=6380, db=0, password='[access-key]', ssl=True)
r.set('foo','bar')
result = r.get('foo')
 
print result 

To start you will need to install redis-py (or a redis client of your choice) from your favourite package installer, I’m using pip.

pip install redis

There are three things you need to be aware of when connecting to Redis on Azure:

  1. SSL
  2. Password
  3. Port

Most of the time when you connect to a redis server it will be on your local machine which is fairly secure because there is no need for an outbound connection to the internet. When connecting to a Cloud Server there are many things that could go wrong in the security department so the Microsoft Azure Redis Cache uses a few things to avoid security issues.

First is a secure connection (SSL), when you connect to Azure you want to ensure that the data going across the wire is encrypted. Second a Password is used to authenticate access with the cache. Finally, the port number has been changed from the default due to the secure connection.

The key when using any Redis library is to ensure that it supports these three things, then once you know that the client supports them, it may still take some investigating to ensure that they are properly enabled when attempting to connect.

When looking at the connection object in python, you’ll notice that SSL is explicitly set to True this is required or you will receive an exception: ConnectionError: Error while reading from socket: (10054, ‘An existing connection was forcibly closed by the remote host’).

Happy Clouding!

Comments are closed.