在文件夹templates创建一个index.html文件:
<html> <head> <title>个人首页</title> </head> <body> <center> <h1>{{user}}, 欢迎你!</h1> <table border="3px"> <tr> <th>课程</th> <th>成绩</th> </tr> <tr> <td>语文</td> <td>{{dic.chinese}}</td> </tr> <tr> <td>数学</td> <td>{{dic.math}}</td> </tr> <tr> <td>英语</td> <td>{{dic.english}}</td> </tr> </table> </center> </body> </html>
在文件夹templates再创建一个login.html文件:
<html> <head> <title>登录界面</title> <meta charset="utf-8"> </head> <body> <center> <form method="post"> <br><br> <input type="text" name="username"><br><br> <input type="text" name="password"><br><br> <input type="submit" value="登录"><br><br> <div style="color: red;">{{Error}}</div><br> </form> </center> </body> </html>
在编辑python文件创建一个服务器:
from flask import Flask, request, render_template, redirect, session, url_for app = Flask(__name__) app.debug = True app.secret_key = "hxd123" user_data = { "hxd": "123", "lw": "123" } score = { "hxd": {"chinese": 60, "math": 78, "english": 70}, "lw": {"chinese": 80, "math": 68, "english": 73} } @app.route("/") def main(): return redirect("/login") @app.route("/index") def index(): try: user = session['user_info'] print(user) except: user = "" if not user: url = url_for('ll') # 反向解析 return redirect(url) print(score[user]) return render_template("index.html", user=user, dic=score[user]) @app.route("/login", methods=['GET', 'POST'], endpoint="ll") def login(): # get请求的数据放在request.query_string # post请求的数据放在request.form if request.method == 'GET': return render_template("login.html") else: username = request.form.get('username') password = request.form.get('password') session['user_info'] = username # if username == "hxd" and password == "123": if username in user_data: if user_data[username] == password: return redirect("/index") else: return render_template("login.html", Error="密码错误!") else: return render_template("login.html", Error="没有该用户!") if __name__ == '__main__': app.run()