Вопрос

I am writing a web app on google app engine with python. I am using jinja2 as a templating engine.

I currently have it set up so that users can upvote and downvote posts but right now they can vote on them as many times as they would like. I simply have the vote record in a database and then calculate it right after that. How can I efficiently prevent users from casting multiple votes?

Это было полезно?

Решение

Store the voting user with the vote, and check for an existing vote by the current user, using your database.

You can perform the check either before you serve the page (and so disable your voting buttons), or when you get the vote attempt (and show some kind of message). You should probably write code to handle both scenarios if the voting really matters to you.

Другие советы

I suggest making a toggleVote method, which accepts the key of the item you want to toggle the vote on, and the key of the user making the vote.

I'd also suggest adding a table to record the votes, basically containing two fields:

"keyOfUserVoting", "keyOfItemBeingVotedOn"

That way you can simply do a very query where the keys match, and if an item exists, then you know the user voted on that item. (Query where keyOfUserVoting = 'param1' and keyOfItemVoted='param2', if result != None, then it means the user voted)

For the toggleVote() method the case could be very simple:

toggleVote(keyOfUserVoting, keyOfItemToVoteOn):
    if (queryResultExists):
        // delete this record from the 'votes' table
    else:
        // add record to the 'votes' table

That way you'll never have to worry about keeping track on an individual basis of how many times the user has voted or not.

Also this way, if you want to find out how many votes are on an item, you can do another query to quickly count where keyOfItemToVoteOn = paramKeyOfItem. Again, with GAE, this will be very fast.

In this setup, you can also quickly tell how many times a user has voted on one item (count where userKey = value and where itemKey = value), or how many times a user has voted in the entire system (count where userKey = value)...

Lastly, for best reliability, you can wrap the updates in the toggleVote() method in a transaction, especially if you'll be doing other things on the user or item being voted on.

Hope this helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top