Search code examples
pythongoogle-app-enginegoogle-cloud-datastoresecurityvoting

More Efficient Way to Prevent Duplicate Voting


There are a few questions similar to this already but I am hoping for a somewhat different answer.

I have a website on Google App Engine in Python and I let registered users vote on posts, either up or down, and I only want each user to be able to vote once.

The primary method that I have thought of and read about is to simply keep a list in each post of the users who have voted on it and only show the voting button to users who have not voted yet. To me this seems like an inelegant solution. To keep track of this when hundreds of people are voting on hundreds of posts is a ton of information to keep track of for such a little bit of functionality.

Though I could be wrong about this. Is this as much of a data/datastore write hog as I am imagining it to be? If I have a few hundred votes going on each day is that not such a big deal?


Solution

  • Create a Vote Kind that looks something like this:

    class Vote(db.Model):
        value = db.IntegerProperty() # Or whatever the vote value is.
    

    The trick is to generate the Key for the vote as a combination of the User and Post ids.

    keyname = str(user.id) + "-" + str(post.id)
    vote = Vote.get_or_insert(keyname, value="vote value")
    

    This way you can quickly check if a user has already voted on a given post.