简体   繁体   中英

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

<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

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

@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?

2, what is the proper way of handling the session, setting timeout etc?

1.

You can use redirect to redirect user to other routes. 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 :

<h1>Dashboard</h1>

Output after inserting admin as username and password:

登录后查看

2.

I would suggest to try Flask-Login for login, logout and login_required functionalities.

From official documentation: login-example using Flask-Login

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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