简体   繁体   English

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

[英]Returning either render_template, or jsonify from Flask as jQuery response

I am trying to create a login page, that after entering incorrect username or password displays an error in the paragraph [working], or redirects the user to the dashboard if the login was successful [not working]. 我正在尝试创建一个登录页面,该页面在输入错误的用户名或密码后会在[正在运行]段落中显示错误,或者,如果登录成功[无法运行],则会将用户重定向到仪表板。

The HTML for the login form looks as follows 登录表单的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>

then I have a JS script that sends a HTTP request to my webserver after hitting the submit button 然后我有一个JS脚本,在点击“提交”按钮后,该脚本将HTTP请求发送到我的网络服务器

$(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;
    }
}

so far all of this works, I get the username and password in my Flask application, where I compare it to the accounts in the DB and if an error occurs, I return a jsonify-ed object with error, otherwise I'd like to make a redirection to the dashboard.html, which doesn't work 到目前为止,所有这些工作正常,我在Flask应用程序中获得了用户名和密码,将其与数据库中的帐户进行了比较,如果发生错误,我将返回一个带有错误的jsonify-ed对象,否则我想重定向到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, any ideas on how to properly redirect after successful login? 1,关于成功登录后如何正确重定向的任何想法?

2, what is the proper way of handling the session, setting timeout etc? 2,处理会话,设置超时等的正确方法是什么?

1. 1。

You can use redirect to redirect user to other routes. 您可以使用redirect将用户重定向到其他路由。 For example: 例如:

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 : dashboard.html

<h1>Dashboard</h1>

Output after inserting admin as username and password: 插入admin作为用户名和密码后的输出:

登录后查看

2. 2。

I would suggest to try Flask-Login for login, logout and login_required functionalities. 我建议尝试使用Flask-Login进行登录,注销和login_required功能。

From official documentation: login-example using Flask-Login 来自官方文档: 使用Flask-Login的登录示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM