作一個用戶登陸以後查看學員信息的小例子

需求:html

1. 用戶名: oldboy 密碼: oldboy123前端

2. 用戶登陸成功以後跳轉到列表頁面flask

3. 失敗有消息提示,從新登陸後端

4.點擊學生名稱以後,能夠看到學生的詳細信息app

 

後端:post

from flask import Flask
from flask import request
from flask import render_template
from flask import redirect

USER = {'username': 'oldboy', 'password': "oldboy123"}

STUDENT_DICT = {
    1: {'name': 'Old', 'age': 38, 'gender': ''},
    2: {'name': 'Boy', 'age': 73, 'gender': ''},
    3: {'name': 'EDU', 'age': 84, 'gender': ''},
}

app = Flask(__name__)


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        if request.form["username"] == USER["username"] and request.form["password"] == USER["password"]:
            return redirect("/student_list")
        return render_template("login.html", msg="用戶名密碼錯誤")

    return render_template("login.html", msg=None)  # 若是前端Jinja2模板中使用了msg,這裏就算是傳遞None也要出現msg


@app.route("/student_list")
def student():
    return render_template("student_list.html", student=STUDENT_DICT)


@app.route("/info")
def student_info():
    stu_id = int(request.args["id"])
    stu_info = STUDENT_DICT[stu_id]
    return render_template("student.html", student=stu_info, stu_id=stu_id)


app.run("0.0.0.0", 5000, debug=True)


 

 

前端:url

login.html:  登陸頁面前端代碼spa

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome to Old Boy EDU</title>
</head>
<body>
    <form method="post">
        用戶名:<input type="text" name="username">
        密碼:<input type="text" name="password">
        <input type="submit" value="登陸">
        {{ msg }}
    </form>
</body>
</html>


 

student_list.html:debug

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Old Boy EDU</title>
</head>
<body>
Welcome to Old Boy EDU
<table border="2xp">
    <thead>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>option</td>
        </tr>
    </thead>
    <tbody>
        {% for foo in student %}
            <tr>
                <td>{{ foo }}</td>
                <td>{{ student[foo].name }}</td>
                <td><a href="/info?id={{ foo }}">詳細</a></td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

一點兒也不難

 

student.htmlcode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Old Boy EDU</title>
</head>
<body>
Welcome to Old Boy EDU
<table border="1px">
    <thead>
    <tr>
        <td>id</td>
        <td>name</td>
        <td>age</td>
        <td>gender</td>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>{{ stu_id }}</td>
        <td>{{ student.name }}</td>
        <td>{{ student["age"] }}</td>
        <td>{{ student.get("gender") }}</td>
    </tr>
    </tbody>
</table>
<div><a href="/student_list">返回</a></div>
</body>
</html>


 

 

思考題:

1.若是我直接訪問 /student_list 和 /student 是否是也能夠?

2.怎麼才能在全部的url地址中校驗是否登陸?

 

第五篇,完結

相關文章
相關標籤/搜索