app.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask, render_template, request, session, redirect, url_for app = Flask(__name__) app.secret_key = "sfsdf35135" # 配合session做登录验证 # app.config.from_object("settings.ProductionConfig") # 登录验证 @app.before_request def test(): if request.path == "/login": return None if session.get("user"): return None return redirect("/login") @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("login.html") user = request.form.get("username") pwd = request.form.get("pwd") if user == "alex" and pwd == "alex123": session["user"] = user return redirect(url_for("index")) return render_template("login.html", error="用户名或密码错误") student_dict = { 1: {"name": "alex123", "age": 34, "gender": "男"}, 2: {"name": "wupeiqi456", "age": 27, "gender": "男"}, 3: {"name": "xiaohua", "age": 24, "gender": "女"}, } @app.route("/index") def index(): return render_template("index.html", stu_id=student_dict) @app.route("/detail/<int:nid>") def detail(nid): data = student_dict.get(nid) return render_template("detail.html", data=data) @app.route("/delete/<int:nid>") def delete(nid): if not nid: return "删除失败" del student_dict[nid] return redirect(url_for("index")) if __name__ == "__main__": app.run()
templates/login.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width initial-scale=1.0"> <title>Title</title> </head> <body> <form action="" method="post"> <input type="text" name="username"> <input type="password" name="pwd"> <input type="submit" value="提交">{{ error }} </form> </body> </html> templates/index.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width initial-scale=1.0"> <title>Title</title> </head> <body> <h1>这是index页面</h1> <table border="1"> <thead> <tr> <th>id</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>操作</th> </tr> </thead> <tbody> {% for k, v in stu_id.items() %} <tr> <td>{{ k }}</td> <td>{{ v.name }}</td> <td>{{ v.age }}</td> <td>{{ v.gender }}</td> <td> <a href="detail/{{ k }}">详细信息</a> <a href="delete/{{ k }}">删除</a> </td> </tr> {% endfor %} </tbody> </table> </body> </html> templates/detail.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width initial-scale=1.0"> <title>Title</title> </head> <body> <h1>这是详细页面</h1> <table border="1"> <thead> <tr> <th>id</th> <th>姓名</th> </tr> </thead> <tbody> {% for k, v in data.items() %} <tr> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>