需求:
1. 用户名: oldboy 密码: oldboy123
2. 用户登录成功之后跳转到列表页面
3. 失败有消息提示,重新登录
4.点击学生名称之后,可以看到学生的详细信息
后端:
1 from flask import Flask 2 from flask import request 3 from flask import render_template 4 from flask import redirect 5 6 USER = {‘username‘: ‘oldboy‘, ‘password‘: "oldboy123"} 7 8 STUDENT_DICT = { 9 1: {‘name‘: ‘Old‘, ‘age‘: 38, ‘gender‘: ‘中‘}, 10 2: {‘name‘: ‘Boy‘, ‘age‘: 73, ‘gender‘: ‘男‘}, 11 3: {‘name‘: ‘EDU‘, ‘age‘: 84, ‘gender‘: ‘女‘}, 12 } 13 14 app = Flask(__name__) 15 16 17 @app.route("/login", methods=["GET", "POST"]) 18 def login(): 19 if request.method == "POST": 20 if request.form["username"] == USER["username"] and request.form["password"] == USER["password"]: 21 return redirect("/student_list") 22 return render_template("login.html", msg="用户名密码错误") 23 24 return render_template("login.html", msg=None) # 如果前端Jinja2模板中使用了msg,这里就算是传递None也要出现msg 25 26 27 @app.route("/student_list") 28 def student(): 29 return render_template("student_list.html", student=STUDENT_DICT) 30 31 32 @app.route("/info") 33 def student_info(): 34 stu_id = int(request.args["id"]) 35 stu_info = STUDENT_DICT[stu_id] 36 return render_template("student.html", student=stu_info, stu_id=stu_id) 37 38 39 app.run("0.0.0.0", 5000, debug=True)
前端:
login.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Welcome to Old Boy EDU</title> 6 </head> 7 <body> 8 <form method="post"> 9 用户名:<input type="text" name="username"> 10 密码:<input type="text" name="password"> 11 <input type="submit" value="登录"> 12 {{ msg }} 13 </form> 14 </body> 15 </html>
student_list.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Old Boy EDU</title> 6 </head> 7 <body> 8 Welcome to Old Boy EDU 9 <table border="2xp"> 10 <thead> 11 <tr> 12 <td>id</td> 13 <td>name</td> 14 <td>option</td> 15 </tr> 16 </thead> 17 <tbody> 18 {% for foo in student %} 19 <tr> 20 <td>{{ foo }}</td> 21 <td>{{ student[foo].name }}</td> 22 <td><a href="/info?id={{ foo }}">详细</a></td> 23 </tr> 24 {% endfor %} 25 </tbody> 26 </table> 27 </body> 28 </html>
student.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Old Boy EDU</title> 6 </head> 7 <body> 8 Welcome to Old Boy EDU 9 <table border="1px"> 10 <thead> 11 <tr> 12 <td>id</td> 13 <td>name</td> 14 <td>age</td> 15 <td>gender</td> 16 </tr> 17 </thead> 18 <tbody> 19 <tr> 20 <td>{{ stu_id }}</td> 21 <td>{{ student.name }}</td> 22 <td>{{ student["age"] }}</td> 23 <td>{{ student.get("gender") }}</td> 24 </tr> 25 </tbody> 26 </table> 27 <div><a href="/student_list">返回</a></div> 28 </body> 29 </html>