将用户限制为一次单个请求 GAE 数据存储



问题

假设用户对一个问题(如 SO)进行投票。makeVote ajax 请求被发送到服务器。当前问题(currentQ)和用户(currentUser)可以从URL和当前会话提供给服务器。如何防止用户一次发送多个请求和多次投票?

我的错误解决方案

阿贾克斯请求

function voteUp(){
    $.ajax({url: "servertools/py/vote?quid="+getUrlParameter('quid')+"&type=quid&a=1", success: function(result){
        $("#questionVotes").html(result);
    }});

Python Request Handler (webapp2)

(我的Student类有一个布尔属性isVoting默认情况下False

currentUser = Student.query(Student.user_id == self.session.get('dbid')).get()
currentQ  = Question.query(Question.qid == self.request.get('quid')).get()
if currentUser.isVoting: # if another request is active
    # write unchanged votes 
    return
# otherwise, no other request is active
currentUser.isVoting = True # set request to currently active. Unsafe for other requests.
currentUser.put()
# perform vote accordingly
currentUser.isVoting = False # current request complete. set request to inactive. Safe for other requests.
currentUser.put()

问题

if currentUser.isVoting:永远不会True

当你执行get()时,你正在创建一个用户类的新实例,以便isVoting 设置为false,并且永远不记得他已经对这个问题进行了投票。

此外,每个问题都应该有一个hasVote指标。否则,您可以在处理其他问题时将他指示为已投票。

您需要创建一个包含所有"当前用户"的列表,其中包含您希望他们保持的状态。然后,当您创建当前用户的新实例(将投票状态设置为 false)时,您需要检查该列表中的用户 ID 并更新状态指示器。否则,当"currrent user"完成时,您将释放类实例,并在用户再次返回投票时将其重置为 false。

您应该在 get() 方法中为用户和问题执行此操作,以便您可以验证当前问题是否尚未被投票。在你的代码中,你应该有一个 get() 选项来表示该问题的投票状态。

请注意,不应直接设置类变量,而应创建将引用类中的类变量的方法。

相关内容

最新更新