1. 程式人生 > >第五篇 練習登入檢視一個班級的學員

第五篇 練習登入檢視一個班級的學員

需求

1. 使用者名稱: oldboy 密碼: oldboy123

2. 使用者登入成功之後跳轉到列表頁面

3. 失敗有訊息提示,重新登入

4.點選學生名稱之後,可以看到學生的詳細資訊

後端:

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

USER = {'username': 'xiaoming', 'password': "123"}

STUDENT_DICT 
= { 1: {'name': 'gangdan', 'age': 38, 'gender': ''}, 2: {'name': 'tiechui, 'age': 73, 'gender': ''}, 3: {'name': 'xiaoming', '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)
View Code

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
    <form method="post">
        使用者名稱:<input type="text" name="username">
        密碼:<input type="text" name="password">
        <input type="submit" value="登入">
        {{ msg }}
    </form>
</body>
</html>
login.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>

<table border="1xp">
    <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_list.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>

<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>
student.html

 

思考題:

1.如果我直接訪問 /student_list 和 /student 是不是也可以?

2.怎麼才能在所有的url地址中校驗是否登入?