模拟简单的登录功能
首先,在app.py
中定义路由,用户访问根路径时,渲染 login.html 页面。输入用户名密码点击提交后,判断用户名密码是否正确,正确则提示登录成功,否则将报错信息显示在页面上
python
from flask import Flask,redirect,url_for,request,render_template
app = Flask(__name__)
# 根路径
@app.route('/')
def index():
return render_template('login.html')
# 登录成功
@app.route('/success/<name>')
def success(name):
return f'welcome {name}!<a href = "/">点击重新登录</a>'
# 直接访问 http://localhost:5000/login ,或者点击提交登录信息后的处理逻辑
@app.route('/login',methods=['POST','GET'])
def login():
error = None
if request.method == 'POST':
user = request.form['username']
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = '用户名或密码错误,请重试!'
else:
print(user)
return redirect(url_for('success',name = user))
return render_template('login.html',error = error)
if __name__ == '__main__':
app.run(debug=True)
login.html
页面入下:
html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="http://localhost:5000/login" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="username" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
{% if error %}
<p><strong>Error</strong>:{{error}}</p>
{% endif %}
</body>
</html>
这样,一个简单的登录功能就做好了。运行app.py,在浏览器输入 http://localhost:5000 即可查看效果。