1. paulc
  2. RedisObject

Source

RedisObject / README


RedisObject
===========

RedisObject provides a 'pythonic' interface to the Redis key-value database
system (http://code.google.com/p/redis/). It provides -

- Interaction directly at the Redis protocol and command level 
- A 'data-mapping' layer which allows implements 'python-like' semantics 
  for scalars/lists/sets over the Redis protocol and allows non-text types 
  to be stored transparently
- An 'object-mapping' layer which allows complex remote-objects and relations
  to be implemented ontop of basic types

The data/object-mapping layers allow Redis to be used in (hopefully) a
transparent & idiomatic way from Python (as a remote 'data-server')

(The module uses the multi-bulk command protocol from Redis 1.1 by default.
For compatibility with Redis 1.0 you must set the 'multibulk' attribute in the
RedisConnection instance to False)

Examples
--------

Basic command level...

    >>> from RedisObject import RedisConnection
    >>> r = RedisConnection()
    >>> r['k1'] = 'v1'
    >>> r['k1']
    'v1'
    >>> r.lpush('l1','a')
    True
    >>> r.lpush('l1','b')
    True
    >>> r.lrange('l1',0,-1)
    ['b', 'a']

More interestingly - using the data-mapping layer...

    >>> from RedisObject import *
    >>> r = RedisConnection()
    >>> l1 = RedisUnicodeList(r,'l1')
    >>> l1.append(u'a')
    >>> l1.append(u'b')
    >>> l1[-1]
    u'b'
    >>> u'a' in l1
    True
    >>> [ x.upper() for x in l1 ]
    [u'A', u'B']
    >>> s1 = RedisIntSet(r,'s1',val=range(10))
    >>> s2 = RedisIntSet(r,'s2',val=range(5,15))
    >>> s1.intersection(s2).sort()
    [5, 6, 7, 8, 9]
    >>> c1 = RedisCounter(r,'c1')
    >>> c1.incr()
    1

Using the object-mapping layer...

    >>> from RedisObject import *
    >>> r = RedisConnection()
    >>> class Collection(RedisObject):
    ...     _attrs = { 'name' : RedisUnicode,
    ...                'items' : RedisObjectList,
    ...                'tag' : RedisUnicode }
    ...     _unique_keys = ['name']
    ...     _keys = ['tag']
    >>> class Item(RedisObject):
    ...     _attrs = { 'name' : RedisUnicode,
    ...                'value' : RedisFloat }
    ...     _unique_keys = ['name']
    >>> i1 = Item(r,name=u'i1',value=1.0)
    >>> i2 = Item(r,name=u'i2')
    >>> i2.value = 99.9
    >>> c1 = Collection(r,name=u'c1',tag=u't1',items=[i1,i2])
    >>> c2 = Collection(r,name=u'c2')
    >>> c2.tag = 't2'
    >>> c2.items.append(i1)
    >>> c3 = Collection(r,name='c3',tag=u't1')
    >>> [ c.name for c in Collection.find(r,tag='t1') ]
    [u'c1', u'c3']
    >>> Collection.find(r,name='c1').items[0].value
    1.0