Flask 登录样例
程序员文章站
2022-07-15 13:05:57
...
from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'adsfasdf'
USERS = {
1:{'name':'wang','age':18,'gender':'man','text':"detail"},
2:{'name':'wei','age':28,'gender':'woman','text':"detail"},
}
@app.route('/login',methods=['GET','POST'],endpoint='l1') # endpoint用于url_for
def login():
if request.method == "GET": # 当get方法访问登录页面,返回登录页面
return render_template('login.html')
else: # 当post方法访问时,则进行判断登录验证
user = request.form.get('user') # 获得form中name="user"对应的值
pwd = request.form.get('pwd') # 获得form中name="pwd"对应的值
if user == 'wang' and pwd == '123': # 判断用户,用户信息可以放在数据库内
session['user_info'] = user # 在session中添加登录的用户,在访问其他页面时可以使用
return redirect('http://www.baidu.com')
return render_template('login.html',error='用户名或密码错误') # 如果登录验证错误,则跳回本页面,并提示
@app.route('/index',methods=['GET'])
def index():
user = session.get('user_info')
if not user:
url = url_for('l1')
return redirect(url)# return redirect('/login')
return render_template('index.html',user_dict=USERS)
@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
user = session.get('user_info')
if not user:
return redirect('/login')
info = USERS.get(nid)
return render_template('detail.html',info=info)
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value="登录">{{error}}
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v['name']}}</td>
<td>{{v.get('name')}}</td>
<td><a href="/detail/{{k}}">查看详细</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>详细信息 {{info.name}}</h1>
<div>
{{info.text}}
</div>
</body>
</html>