【问题标题】:How to i prevent my code from producing a syntax error on my else statement如何防止我的代码在我的 else 语句中产生语法错误
【发布时间】:2017-12-15 05:08:47
【问题描述】:

您好,这是我的第一篇文章,我对 Python 编码还很陌生(6 个月)。我一直在研究这个烧瓶应用程序,并在最后一行的 else 语句中不断遇到语法错误。我已经看到答案说这可能是一个缩进问题,但我已经尝试过该解决方案但没有成功。我确信这个问题有一些非常明显的东西,但是在开始和停止几次之后,我似乎无法发现它。请帮忙

示例代码:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""

    if request.method == "POST":
        if not request.form.get("username") or not request.form.get("password"):
            return apology("Provide Username AND Password Silly!")
        elif not request.form.get("password2"):
            return apology("Must Confrim Password")
        elif request.form.get("password2") != request.form.get("password"):
            return apology("Passwords Didn't Match")

        hashi, username = pwd_context.encrypt(request.form.get("password")), request.form.get("username")

        CheckUsername = db.execute("INSERT INTO \
        users (username, hashi) VALUES(:username :hashi)", \
        username=username, hashi=hashi)
        if not CheckUsername:
            return apology("username already exist")

        CheckNow = db.execute("SELECT * FROM users WHERE username = :username", username=username)
        if not CheckNow:
            return apology("Something Bad Happened, Let Us Know")

        session["user_id"] = CheckNow[0]["id"]
        return redirect(url_for("history")
    else:
        return render_template("register.html")

【问题讨论】:

  • 上一行 return redirect(url_for("history") 缺少右括号。
  • 如果我的回答解决了您的问题,请考虑投票给它:)

标签: python if-statement flask syntax indentation


【解决方案1】:
return redirect(url_for("history")

在这一行的末尾需要一个括号。


为了避免语法错误,可以使用一些IDE来防止错误和警告,并提供PEP 8标准,例如:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多