全部博文(921)
分类: Python/Ruby
2011-03-30 14:11:13
So just yesterday we posted a tutorial on how to use redis to. Soon after we published the documentation on the new redis hash type went online. Now hashes by themselves aren’t exactly relations but, more so an object field store. Extending the same concepts from our first article in namespace utilization and using hashes we can accomplish the same thing in a more formal fashion.
We will repeat the same exercise from the first article, creating a username password store, using hashes.
Basic hash overview
Without going into the technical details we can simplify the concept of redis’s as a way to store fields in a redis key. In Pythonic terms we can make a redis key into a basic Python .
[key] : {‘field’ -> ‘value’, ‘field’ -> ‘value’, ‘field’ -> ‘value’}
Basic hash usage
We will break it down line by line here
As you can see, this is an excellent way to store information about an object without “faking” a relation like in our previous tutorial.
As I mentioned in the conclusion of the last article, if we want to change how we store information in redis all we should have to do is to change is change the inner workings of the functions add_user, authenticate_user, delete_user and the rest of our fictitious application should operate without any changes.
Creating a new user
I left the original code in the function commented out so we can see the differences in the two methods here. In our original method we used the name space of redis itself to store the reference. In the updated fashion we are using redis’s hash data type to store the related fields.
This function operates in the same fashion as our old version did but, is using a different data structure in the backend.
Logging a user inNow we’ll refactor our old authentication code to work with the new backend.
Just as in the add_user function, we just need to make a small change. Now instead of fetching the related redis key we simply fetch the field from the hash of “user:*username*”.
>>> authenticate_user("adam", "wealthofnations") |
2 | True |
3 | >>> authenticate_user("adam", "bad_password") |
4 | False |
We can see the function again performs just like the old function but, it pulls the password from the hash object instead of the related key
Deleting a userDeleting a user using the hash store is much easier than using the related key store, since everything is just stored in one key instead of being spread out across multiple keys.
Now instead of having to delete the 2 related keys, we just need to delete the one key storing the hash of all of the user data
文章来自: