Description

Redmodel is born as an alternative to Redisco. It’s focused on model
relationships and indexes, and tries to be a thin but powerful layer on top of
redis.

The concepts of Handle and Writer are introduced, which make redmodel less
magic than redisco, but allow a finer control on what you are doing:

A handle is a reference to an object stored in redis. A query, for instance,
returns a handle or a set of handles, and does not load automatically the
objects from redis. You must load them explicitly.

A writer is an object used to write model objects or containers. The main
reason for this is to allow writing code which only reads some models data,
but is not able to write them. That’s good to divide responsibilities in
different modules, threads, or programs.

Test-driven development was used to create Redmodel, so it is and will be
extensively tested by automated tests located in the test directory.
I recomend you read the testing code if you want to understand the internals
of Redmodel.

Model Definition

These example models have been created to test all redmodel features. They
model the data of an hypothetic game of gangs, whose members are fighters
which move along different cities. A game extension adds a skill system to
the fighters.

from redmodel.models import Model, Attribute, BooleanField, IntegerField, FloatField, UTCDateTimeField
from redmodel.models import ReferenceField, ListField, SetField, SortedSetField, Recursive
# City with a name, a boolean, and a list of connections to other cities
# (recursive references).
class City(Model):
name = Attribute()
coast = BooleanField()
connections = ListField(Recursive)
# Weapon with a description and its power value.
class Weapon(Model):
description = Attribute()
power = FloatField()
# Fighter with name, age, weight, join time, and current city.
# - The name is defined as unique, so fighters are indexed by name (we can
# find a fighter by name), and it cannot be repeated. The index is a
# redis hash.
# - The datetime field is stored as an integer (no microseconds). It may be
# better to use an IntegerField directly, in order to avoid conversions.
# - The current city is indexed, so we can find which fighters are in a
# city. This index is a collection of redis sets.
# - Attributes which are zindexed have a redis sorted set associated, so we
# can execute queries like Fighter.zfind(age__lt = 30).
# - Weapons are sorted by power. In this case, we have a redis sorted set
# for every Fighter object (with zindexed, we have one global sorted set).
# - The weapons field could have been created as:
# weapons = SortedSetField(Weapon)
# So entries are not sorted by a specific field, but a 'score' must be
# specified as an additional parameter.
# If a field is specified, then owned must be True (see below for an
# explanation about 'owned'), and a weapon's power should not be updated
# directly, but using SortedSetFieldWriter's update or update_all methods,
# so the sorted set is automatically and atomically updated.
class Fighter(Model):
name = Attribute(unique = True)
age = IntegerField(zindexed = True)
weight = FloatField(zindexed = True)
joined = UTCDateTimeField(zindexed = True)
city = ReferenceField(City, indexed = True)
weapons = SortedSetField(Weapon, Weapon.power, owned = True)
# Gang with a name and a set of member fighters.
# - A fighter can only be the leader of one gang. This index is a redis
# hash.
# - Members are indexed uniquely. That means a fighter can be in one gang
# only. This index is a single redis hash.
# - Cities where the gang operates are indexed, so we can find which gangs
# operate in a city. This index is a collection of redis sets.
# - The headquarter city (hqcity) is listed: This means that redis lists
# exist containing gangs with their headquarters in each city. This is
# similar to indexed, but a list is used instead of a set. This is great
# to keep the elements sorted by creation time, but it's bad for removing
# or searching.
class Gang(Model):
name = Attribute()
leader = ReferenceField(Fighter, unique = True)
members = SetField(Fighter, unique = True)
cities = SetField(City, indexed = True)
hqcity = ReferenceField(City, listed = True)
# Skill that fighters can have.
class Skill(Model):
category = Attribute()
name = Attribute()
description = Attribute()
# Skill instance: a skill with a value.
class SkillInstance(Model):
skill = ReferenceField(Skill)
value = IntegerField()
# Skills a fighter has.
# - This model is owned by the Fighter model ("owner = Fighter"). So, this
# model is an extension to the Fighter model. This is useful to implement
# plugins or independent modules with independent data, instead of
# modifying the base model (Fighter in this example).
# - SkillInstance objects in the skills list are owned by this model
# ("owned = True"). This means that:
# 1. New SkillInstance objects can be created and added to the list
# atomically.
# 2. An object removed from the list is deleted automatically.
class FighterSkillList(Model):
owner = Fighter
skills = ListField(SkillInstance, owned = True)

Add some weapons to fighter f1. Notice that we attach weapon_writer to
fighter_weapons_writer as the “element_writer”, so objects are created and
deleted automatically (we can do this because the “weapons” container of
Fighter has “owned = True”). Furthermore, this will be useful when updating
the objects to keep the set sorted (see later):

Reading Data

We can build a handle for an object by id. This implies no access to redis.
If the object does not exist, the handle is valid anyway:

handle = Gang.by_id(1)

To read the data from redis, we create a model object, passing a handle to the
constructor:

gang = Gang(handle)

Container fields (lists, sets and sorted sets) are not read automatically from
redis. Instead, a handle for the container is generated in the owner object.
They are loaded using the List, Set and SortedSet classes from
redmodel.containers. A List, Set or SortedSet object contains a collection
of object handles (but notice that containers of elementary types can also
exist).

This is how we list the gang member fighters:

from redmodel.containers import Set
members = Set(gang.members)
for handle in members:
print(str(Fighter(handle)))

SortedSet has some query methods in addition to the read constructor.
These methods wrap z* redis functions (plus the convenience zfind method).
These are further explained in the Containers section. So, we can make some
queries on a fighter weapon set:

Queries

hbob = Fighter.find(name = 'Bob')
if not hbob:
print('Fighter not found.')
# trying to read from an invalid handle would raise NotFoundError,
# so we can do this instead:
from redmodel.models import NotFoundError
try:
fighter = Fighter(Fighter.find(name = 'Bob'))
except NotFoundError:
print('Fighter not found.')

Find in non unique index:

# find all fighters which are currently in city number 1;
# the result is a set of Fighter handles
city_fighters = Fighter.multifind(city = City.by_id(1))

For fields which are ‘listed’ instead of ‘indexed’, use getlist:

# find all gangs with headquarters in a given city
gangs_by_hqcity = Gang.getlist(hqcity = City.by_id(3))
# get the first 10 elements only
first_gangs_by_hqcity = Gang.getlist(0, 9, hqcity = City.by_id(3))

Find in unique container index:

bobs_gang = Gang(Gang.find(members__contains = hbob))

Find in non unique container index:

# find all gangs which operate in city number 3;
# the result is a set of Gang handles
city_gangs = Gang.multifind(cities__contains = City.by_id(3))

Queries on Sorted Indexes

For fields which are zindexed, methods that wrap z* redis functions are
available (similar to those on sorted set fields explained before).
These methods return a sorted list of handles:

# get a list of Fighter handles sorted by fighters weight
# (notice there's no sorting operation here; we are keeping a sorted index)
sorted_by_weight = Fighter.zrange('weight')
# get the top ten heaviest fighters
heaviest_fighters = Fighter.zrevrange('weight', 0, 9)
# get list of fighters less or equal than 24 years old
# (notice you can use zfind for this; see below)
young_fighters = Fighter.zrangebyscore('age', '-inf', 24)
# get first 3 fighters greater than 39 years old (39 not included)
mature_fighters = Fighter.zrangebyscore('age', '(39', '+inf', 0, 3)

# count fighters in an age range
Fighter.zcount('age', 20, 23)
# get position of fighter in zero-based weight ranking (increasing order)
Fighter.zrank('weight', fighter1)
# get position of fighter by handle in weight ranking (decreasing order)
Fighter.zrevrank('weight', hfighter2)

Updating Data

Object attributes can be updated in two ways:
(notice that indexes are updated automatically)

Delete an object. Notice that containers referencing this object will contain
now an invalid handle! Use container fields with “owned = True” whenever
possible, so objects are deleted automatically when removing its handle from
the container.