Skip to content

Instantly share code, notes, and snippets.

@adamcharnock
Created October 19, 2010 17:34
Show Gist options
  • Save adamcharnock/634624 to your computer and use it in GitHub Desktop.
Save adamcharnock/634624 to your computer and use it in GitHub Desktop.

We have been covering some fairly complex Redis topics here so far, so I thought it would be nice to do a good ol’ getting started guide. This should get you on your feet with Python and Redis on Ubuntu Linux. So, fire up a terminal window and get going!

Getting Redis installed & running

This guide uses Redis 2.0.3, but you can see if there is a newer version at redis.io:

apt-get install build-essential

wget http://redis.googlecode.com/files/redis-2.0.3.tar.gz
tar -zxf redis-2.0.3.tar.gz
cd redis-2.0.3
make

Nice work, you have just compiled Redis! All you need to do now is start it up:

./redis-server

This will run Redis in the foreground, so now would be a good time to fire up a second terminal window. You can check everything is running ok by running:

echo "INFO" | nc localhost 6379

You should see a bunch of Redis status information for you to enjoy at your leisure.

Connecting with Python

Now we just need to get ourselves a Redis Python client, and here we will be using redis by Andy McCurdy, the same client that we use for PlayNice.ly:

apt-get install python-setuptools
easy_install redis

Note: This is a pretty basic way of installing packages. See our blog post on Pip & Virtualenv for something more wholesome.

All done? Good. Now just fire up a Python prompt (just type ‘python’ on the command line) and…

from redis import Redis
>>> r = Redis()
>>> r.set("test-key", 123456)
True
>>> r.get("test-key")
'123456'

Great! If you have come this far then you are pretty much sorted. You can find a full list of commands on the package’s Github page. But just to get you started, here is how you can interact with the LIST data type:

from redis import Redis
>>> r = Redis()
>>> r.rpush("my-list", "yellow") # put some values into a list (the key is created implicitly)
1
>>> r.rpush("my-list", "blue")
2
>>> r.rpush("my-list", "green")
3
>>> r.rpush("my-list", "red")
4
>>> r.lrange("my-list", 0, 4) # get all 4 keys
['yellow', 'blue', 'green', 'red']
>>> r.sort("my-list", alpha=True) # sort alphanumerically
['blue', 'green', 'red', 'yellow']
>>> r.lset("my-list", 1, "cyan") # change index 1 (blue) to 'cyan'
True
>>> r.lrange("my-list", 0, 4)
['yellow', 'cyan', 'green', 'red']

There is loads more that you can do with Redis, so go and have an explore. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment