"Simplicity is the ultimate sophistication."
-- Leonardo Da Vinci
Redis is an open source, 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.
class Pagination(object):
# len(pagination_homepage))
def __len__(self):
redis.zcard(self.get_key())
# pagination_homepage[10:20]
def __getitem__(self, k):
return db.get_by_pk(
redis.zrevrangebyscore(
self.get_key(), # pagination_homepage
time.time(), 0, # now() - 0
k.start, k.stop, # 10 - 20
)
)
# publisher:
redis.rpush(QUEUE_NAME, task)
# worker:
while True:
task = redis.blpop(QUEUE_NAME)
do_something(task)
slaveof redis-master.example.com 9000
def publish(message):
action_time = time.time()
# run all redis queries in a pipe
pipe = redis.pipeline()
# add the actions to the master zset
pipe = pipe.zadd(ACTIONS_KEY, message, action_time)
# trim the zset to only contain 30 actions
pipe = pipe.zremrangebyrank(ACTIONS_KEY, 0, -31)
# execute everything at once
pipe.execute()
# publish to all clients waiting for a message
redis.publish(BROADCAST_KEY, message)
def poll(last_seen):
# last_seen - retrieve only new actions
actions = redis.zrangebyscore(ACTIONS_KEY,
min='(%f' % last_seen, max=time.time(), withscores=True)
if actions:
return actions
# no new actions stored in redis, wait for them
pubsub = redis.pubsub()
pubsub.subscribe(BROADCAST_KEY)
try:
message = pubsub.listen().next():
except ConnectionError: # timeout
return []
else:
return [message]
finally:
pubsub.unsubscribe()
????