需求:
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 = {
: {'name': 'Old', 'age': , 'gender': '中'},
: {'name': 'Boy', 'age': , 'gender': '男'},
: {'name': 'EDU', 'age': , '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", , 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>
字典形式学生信息
第五篇,完结