使用python flask登录应用程序而不是重定向到登录页面

时间:2015-12-24 08:07:30

标签: python html mongodb

我正在后端使用python flask和mongodb创建一个登录应用程序,一切正常但在登录时它不会重定向到登录页面。

#here is my code
@app.route('/login/', methods=["GET","POST"])
def login_page():
    error = ''
    try:
       conn = connection()
       collection=MongoClient()["blog"]["users"]
       if request.method == "POST":

        data = collection.find({"username":(request.form['username'])})
        #data1=collection.find({"password":(request.form['password'])})
        if sha256_crypt.verify(request.form.password,data):
            print("password verification suceessful")
            session['logged_in'] = True
            session['username'] = request.form['username']

            flash("You are now logged in")
            return redirect(url_for("dashboard"))

        else:
            error = "Invalid credentials, try again."

    gc.collect()

    return render_template("login.html", error=error)

except Exception as e:

    error = "Invalid credentials, try again."
    return render_template("login.html", error = error)

在这里,我试图验证用户输入的用户名和密码是否与我的数据库集合匹配。如果匹配,用户可以登录其他抛出一个错误messgae并重定向到登录页面。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是我的问题的答案,

@app.route('/login/', methods=["GET","POST"])
def login_page():
    error = ''
    try:
        conn = connection()
        collection=MongoClient()["blog"]["users"]
        if request.method == "POST":
            #collection = MongoClient()["blog"]["users"]

            data = collection.find_one({"username":(request.form['username'])})
            #data1=collection.find({"password":(request.form['password'])}
            #data = c.fetchone()[2]
            password=request.form['password']
            if sha256_crypt.verify(password,data['password']):
                print("password verification suceessful")
                session['logged_in'] = True
                session['username'] = request.form['username']

                flash("You are now logged in")
                return redirect(url_for("dashboard"))

            else:
                error = "Invalid credentials, try again."

       # gc.collect()

        return render_template("login.html", error=error)

    except Exception as e:
        #flash(e)
        error = "Invalid credentials, try again."
        return render_template("login.html", error = error)