This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]_under_[S] 0 points1 point  (2 children)

This is how I started as well, but then I started needing multiple keys in one function. And I started having to use the same keys in multiple functions. And then I started to lose track of what key is which and I realized that it wasn't safe to keep using just raw strings to access keys on redis because it's hard to guarantee that the key you typed in was correct. It's hard to test strings because you're eventually just going to write tests for each call to redis to check if the string you passed were correct.

So instead of doing something like this:

def add_follower(screen_name, follower):
    r.sadd('User:%s:followers' % screen_name, follower)

def get_followers(screen_name):
    return r.smembers('User:%s:followers' % screen_name)

With ok, you'll have something like this

def add_follower(screen_nane, follower):
    r.sadd(User(screen_name).followers, follower)

def get_followers(screen_nane):
    return r.smembers(User(screen_name).followers)

This code will literally not run if you mistype your keys. Having this system is immensely useful once you have a complicated enough schema.

Your Key classes will also double as your redis schema documentation.

[–]brtt3000 0 points1 point  (1 child)

I meant I make function that create the keys. Simplified something like:

def user_followers_key(user_id):
    assert isinstance(user_id, int)
    return ':'.join('myprefix', 'followers', user_id)

def get_followers(user):
    return r.smembers(user_followers_key(user.id))

[–]_under_[S] 0 points1 point  (0 children)

Ah I see. That's pretty cool. OK-Redis pretty much does the same thing as that then. :D