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

Evaluating user input before making a new database query

我正在使用 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>

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

  • 得到一个随机问题
  • strip 提供的响应。

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

  • 用户点击 link 到 "Start" 玩游戏,因此刚刚登陆页面。
  • 用户已提交表单,您必须评估他的回复

为此,您必须将问题 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 的值,您可以在模板中显示 "Correct!" 或 "Wrong :(" 消息。