在进行新数据库查询之前评估用户输入

时间:2016-11-24 03:30:42

标签: python bottle

我正在制作一个带瓶子的小琐事游戏,我遇到了一些麻烦。 页面加载,一个随机的琐事问题从数据库中拉出并出现在浏览器中,当页面首次加载时,服务器会自动尝试从表单输入中获取值,输入为空(这并不奇怪)。但是,如果我尝试在输入字段中输入琐事问题的答案,然后单击“提交”按钮,页面将重新加载,并从数据库中获取下一个琐事问题。我的用户输入永远不会匹配当前的琐事问题,因为它始终保持前一个问题的值。

如何在没有提交页面重新加载并生成新的随机查询的情况下从特定数据库查询的用户输入中获取值?

在我的game.py文件中:

@app.route("/game", method=["POST"])
def game(db):
   db.execute("select * from questions order by rand() limit 1")
   data = db.fetchall()
   guess = ""
   name = ""
   for d in data:
      country_name = d["name"]

   if request.POST.the_guess:
      guess = request.POST.the_guess.strip()

return bottle.template("temp", data=data)

在我的temp.tpl

<form method="POST" action="/game"> <input type="text" name="the_guess"> <input type="submit" value="guess"> </form>

1 个答案:

答案 0 :(得分:1)

无论用户是否提交表单,您的请求视图都会做同样的事情,即

  • 随机提问
  • strip提供的回复。

但是,您必须考虑两种情况

  • 用户点击“开始”玩游戏的链接,因此刚刚登陆页面。
  • 用户已提交表单,您必须评估其转发

为此,您必须将问题ID作为隐藏字段传递,以便了解正确的答案。

<form method="POST" action="/game">
    <input type="text" name="the_guess">
    <input type="submit" value="guess">
    <input type="hidden" name="qid" value="YOUR_QUESTION_ID">
</form>

因此,视图代码必须执行类似的操作(我不知道Bottle视图的正确语义,因此请将其视为伪代码):

@app.route("/game", method=["POST", "GET"])
def game(db):
   # Store if user answered last question correctly or not
   user_feedback = None
   # See if this view is beng invoked by user submitting an answer
   if "submit" in request.POST:
       guess = request.POST.the_guess.strip()
       qid = request.POST.qid
       # Lookup DB for answer of question with ID qid. Store it as answer
       if guess == answer:
           user_feedback = True
       else:
           user_feedback = False
   # This part will always execute
   db.execute("select * from questions order by rand() limit 1")
   data = db.fetchall()
   for d in data:
      country_name = d["name"]         
   return bottle.template("temp", data=data, user_feedback=user_feedback)

根据user_feedback的值,您可以在模板中显示“正确!”或者“错误:(”消息。