Home > python > redis: getting started

redis: getting started

Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.” (source)

Also, redis commands are atomic operations.


# Check out the home page for the latest version!
$ wget http://redis.googlecode.com/files/redis-2.6.14.tar.gz
$ tar xvzf redis-2.6.14.tar.gz
$ cd redis-2.6.14
$ make
$ sudo make install

Then start the redis server:

$ redis-server

The server, by default, will listen on localhost:6379.

Graphical interface
Do you like phpMyAdmin? Well, there is something similar to redis too called Redis Commander. Check out the project’s home page for installation instructions.

Redis Commander is written in node.js. For installing node.js, refer to this post: Installing Node.js and NPM on Ubuntu/Debian.

Python binding
At this point you might ask the natural question: “OK, but how can I use it from Python?”. You need the following client:

sudo pip install redis -U

Let’s test it:

>>> import redis
>>> r = redis.Redis()    # default: localhost, port 6379
>>> r.set("name", "jabba")
>>> r.get("name")

Let’s see another example with a list:

>>> import redis
>>> r = redis.Redis()
# the list is called "test"
# rpush: right push, i.e. put an element on its right side (tail)
>>> r.rpush("test", 24)
>>> r.rpush("test", 67)
>>> r.rpush("test", 9)
# list all the elements (-1 is the index of the last element)
>>> r.lrange("test", 0, -1)
['24', '67', '9']
# number of elements 
>>> r.llen("test")
# delete the list if you don't need it anymore
>>> r.delete("test")

Save the database
It is possible to save the database to disk. When you restart the server, it can restore the database from disk.

The database will be saved to the directory where you started redis! For instance, you started redis from your HOME directory. In a Python script you called “r.save()“, which creates a snapshot of the database and dumps it to “~/dump.rdb“. When you start the server, it checks for this dump file in the current directory. If “./dump.rdb” is found, it will be loaded.

If you run redis-server in a terminal, check out its log. It will indicate if it found and loaded a database upon startup.


Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: