登录功能完成:

  1. js:设置return
  2. html:设置
    1. form
    2. input
  3. py:
    1. @app.route设置methods
    2. GET
    3. POST
      1. 读取表单数据
      2. 查询数据库
        1. 用户名密码对:
          1. 记住用户名
          2. 跳转到首页
        2. 用户名密码不对:
          1. 提示相应错误。

session:

  1. 从`flask`中导入`session`
  2. 设置`SECRET_KEY`
  3. 操作字典一样操作`session`:增加用户名`session['username']=`username
 1 from flask import Flask, render_template, request, redirect, url_for, session
 2 from flask_sqlalchemy import SQLAlchemy
 3 import config
 4 
 5 app = Flask(__name__)
 6 app.config.from_object(config)
 7 db = SQLAlchemy(app)
 8 
 9 
10 class User(db.Model):
11     __tablename__ = 'user'
12     id = db.Column(db.Integer, primary_key=True, autoincrement=True)
13     username = db.Column(db.String(20), nullable=False)
14     password = db.Column(db.String(20), nullable=False)
15     nickname = db.Column(db.String(50))
16 
17 
18 # user = User(username = 'misjiaojiao',password = 'misjiaojiao')
19 # db.session.add(user)
20 # db.session.commit()
21 
22 # user = User.query.filter(User.username == 'misjiaojiao').first()
23 # db.session.delete(user)
24 # db.session.commit()
25 
26 # user = User.query.filter(User.username == 'misjiaojiao').first()
27 # user.password='1234657'
28 # db.session.commit()
29 
30 # db.create_all()
31 
32 @app.route('/')
33 def index():
34     return render_template('switch切换.html')
35 
36 
37 @app.route('/login/', methods=['GET', 'POST'])
38 def login():
39     if request.method == 'GET':
40         return render_template('login登录.html')
41     else:
42         usern = request.form.get('username')
43         passw = request.form.get('password')
44         user = User.query.filter(User.username == usern).first()
45         if user:
46             session['user'] = usern
47             session.permanent = True
48             return redirect(url_for('index'))
49         else:
50             return u'error username or password'
51 
52 
53 @app.route('/regist/', methods=['GET', 'POST'])
54 def regist():
55     if request.method == 'GET':
56         return render_template('regist注册.html')
57     else:
58         username = request.form.get('username')
59         password = request.form.get('password')
60         nickname = request.form.get('nickname')
61         user = User.query.filter(User.username == username).first()
62         if user:
63             return u'username existed'
64         else:
65             user = User(username=username, password=password, nickname=nickname)
66             db.session.add(user)  # 数据库操作
67             db.session.commit()
68             return redirect(url_for('login'))
69 
70 
71 if __name__ == '__main__':
72     app.run(debug=True)
1 import os
2 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/mis_db?charset=utf8'
3 SQLALCHEMY_TRACK_MODIFICATIONS = False
4 SECRET_KEY = os.urandom(24)

 

posted on 2017-11-21 09:56  016李云基  阅读(157)  评论(0编辑  收藏  举报