第五篇 做一个用户登录之后查看学员信息的小例子
需求:
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': '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) 相信写的代码才是最好的
前端:
login.html:
<!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:
<!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.html
<!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地址中校验是否登录?
第五篇,完结