Flask项目之login提交

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2019/11/2 20:53
 4 # @Author  : zoulixiang
 5 # @Site    : 
 6 # @File    : s2.py
 7 # @Software: PyCharm
 8 
 9 from flask import Flask,render_template,request,redirect,session,url_for
10 
11 app = Flask(__name__)
12 #自动重启和检测,调试模式
13 app.debug = True
14 
15 USERS = {
16     1:{'name':'z','age':12,'gender':'','text':'ssssssss'},
17     2:{'name':'z1','age':13,'gender':'','text':'xxxxxxxx'},
18     3:{'name':'z1','age':14,'gender':'','text':'hhhhhhhh'}
19 }
20 
21 @app.route('/detail/<int:nid>',methods=['GET'])
22 def detail(nid):
23     # 当你登录成功之后,session是有值,有值之后上面每个登录都需要重新判断
24     user = session.get('user_info')
25     if not user:
26         return redirect('/login')
27     info = USERS.get(nid)
28     return render_template('detail.html',info=info)
29 
30 
31 @app.route('/index',methods=['GET'])
32 def index():
33     #session #当你登录成功之后,session是有值,有值之后上面每个登录都需要重新判断
34     user = session.get('user_info')
35     if not user:
36         #反向生成url
37         url = url_for('l1')
38         return redirect(url)
39     return render_template('index.html',user_dict=USERS)
40 
41 
42 @app.route('/login',methods=['GET','POST'],endpoint='l1') #endpoin 别名
43 def login():
44     if request.method == "GET":
45         return render_template('login.html')
46     else:
47         user = request.form.get('user')
48         pwd = request.form.get('pwd')
49         if user == 'alex' and pwd == '123':
50             #当你登录成功之后,session是有值,有值之后上面每个登录都需要重新判断
51             session['user_info'] = user
52             print(session['user_info'])
53             return redirect('https://www.baidu.com')
54         return render_template('login.html',error = '用户名或密码错误')
55 
56 if __name__ == '__main__':
57     app.run()

 


 

 



2.tmplates目录
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" name="登录">{{error}}
    </form>

</body>
</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}} {{v['name']}} {{v.get('name')}} </td>
            <td><a href="/detail/{{k}}">查看详细</a></td>
        </tr>
        {% endfor %}
    </table>

</body>
</html>

  

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>详细信息</h1>
    <div>
        {{ info.name }}
        {{ info.text }}
    </div>

</body>
</html>

  


 

posted @ 2019-11-03 21:03  Mr.zou  阅读(236)  评论(0编辑  收藏  举报