从Flask返回render_template或jsonify作为jQuery响应

时间:2018-11-28 15:03:06

标签: python flask

我正在尝试创建一个登录页面,该页面在输入错误的用户名或密码后会在[工作]段落中显示错误,或者如果登录成功[不工作],则将用户重定向到仪表板。

登录表单的HTML如下

<form id="login" action="/login" method="post">
    <fieldset>
        <legend>Login to the Metalworks</legend>
        Username:<br>
        <input type="text" name="username"><br>
        Password:<br>
        <input type="password" name="password"><br><br>
        <input type="submit" value="Login">
    </fieldset>
</form>
<br>
<p id="result" style="font-size:24px; font-weight:bold"></p>

然后我有一个JS脚本,该脚本在单击“提交”按钮后将HTTP请求发送到我的Web服务器

$(document).ready(function() {
    $("#login").ajaxForm({
        url: "/login",
        dataType: "json",
        success: loginResult
    });
});

function loginResult(response)
{
    result = document.getElementById("result");
    if (!response.success)
    {
        result.style.color = "red";
        result.innerHTML = response.error;
    }
}

到目前为止,所有这些工作正常,我在Flask应用程序中获得了用户名和密码,将其与数据库中的帐户进行了比较,如果发生错误,我将返回一个带有错误的jsonify-ed对象,否则我将d想要重定向到dashboard.html,这是行不通的

@app.route("/")
def home():
    return render_template("login.html", title="Metalworks Login");

@app.route("/login", methods = ["POST"])
def login():
    if "username" not in request.form or len(request.form["username"]) == 0: return jsonify({"success":False, "error":"Username is not specified!"});
    if "password" not in request.form or len(request.form["password"]) == 0: return jsonify({"success":False, "error":"Password is not specified!"});

    username = request.form["username"];
    password = request.form["password"];

    cursor = accountsCollection.find({"username":username});
    try:
        account = cursor[0];
    except:
        return jsonify({"success":False, "error":"Could not find account {}!".format(username)});

    if account["password"] != password:
        return jsonify({"success":False, "error":"Incorrect password!"});

    # this does nothing
    return render_template("dashboard.html", title="Metalworks Dashboard");

1,关于成功登录后如何正确重定向的任何想法?

2,处理会话,设置超时等的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

1。

您可以使用redirect将用户重定向到其他路由。 例如:

from flask import Flask, render_template, request, redirect, jsonify

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("login.html", title="Metalworks Login")

@app.route("/dashboard")
def dashboard():
    return render_template("dashboard.html", title="Metalworks Login")


@app.route("/login", methods = ["POST"])
def login():
    if "username" not in request.form or len(request.form["username"]) == 0: return jsonify({"success":False, "error":"Username is not specified!"})
    if "password" not in request.form or len(request.form["password"]) == 0: return jsonify({"success":False, "error":"Password is not specified!"})

    username = request.form["username"]
    password = request.form["password"]
    account = {"username": "admin", "password": "admin"}
    if account["username"] != username or account["password"] != password:
        return jsonify({"success":False, "error":"Incorrect password!"})

    return redirect("/dashboard")

app.run(debug=True)

dashboard.html

<h1>Dashboard</h1>

在插入admin作为用户名和密码后的输出:

after login view

2。

我建议尝试Flask-Login进行登录,注销和login_required功能。

摘自官方文档:login-example using Flask-Login