Reputation: 2011
I have a django app. The app is a normal application. Everything is running fine for me.
I want to implement a leaderboard as of now. Read couple of places that redis helps in doing it. And is really awesome. So I installed and configured redis on the server.
A minimal representation of the user profile for me is:
class UserProfile(models.Model):
user = models.OneToOneField(User)
invited_friends = models.BooleanField(default=False)
filled_wishlist = models.BooleanField(default=False)
upvote = models.IntegerField()
downvote = models.IntegerField()
@property
def reputation(self):
return int(confidence_fixed(self.upvote, self.downvote)*100)
Based on this reputation property, I get a value. All this is happening at the PostgreSQL db backend.
Now what I want to do is, take these scores, put them in redis key value store, and generate a leaderboard. There is a superawesome redis library for implementing leaderboard: https://github.com/agoragames/leaderboard-python
So my question is, given my redis server is running say at XXX.XXX.XX.XX:6342
How do I connect my python/django app to the redis server, and update the KV store, and once there are some numbers, how do I fetch in a view and display?
Upvotes: 2
Views: 749
Reputation: 1422
For future googlers, the way to tell Leaderboard how to connect to your redis server is by specifying a few more arguments in the Leaderboard constructor:
reputation_lb = Leaderboard('reputation', host="xyz.com", port="1234")
More details about what options are supported can be found in constructor code for Leaderboard here: http://pydoc.net/Python/leaderboard/2.8.0/leaderboard/
Upvotes: 0
Reputation: 776
I think you're on the right track with the leaderboard-python library.
First you would need to write a onetime script to move the data from your model to redis using leaderboard-python.
# Create a new leaderboard
reputation_lb = Leaderboard('reputation')
for profile in UserProfile.objects.all():
reputation.rank_member('user_%i' % profile.user.pk, profile.reputation)
You would also need to create another property on the UserProfile model that retrieves the reputation from leaderboard-python.
Then you would most likely want to update the score, either you duplicate the information in the database and continue to use your reputation property to update the leaderboard, or you simply increment/decrement the score stored in redis.
The readme of the leaderboard-python library is quite good and should contain all of the examples you need to build this.
Upvotes: 1