登陆需要账号密码,之前只写了账号,现在把密码加进去,修改models.py:
from . import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
# 如果你学过数据库的话就知道我们一般通过id来作为主键,来找到对应的信息的,通过id来实现唯一性
username = db.Column(db.String(64), unique=True)
password = db.Column(db.String(64))
def __repr__(self):
return 'users表: id为:{}, name为:{}'.format(self.id, self.username)
只有在密码和账号都输入了的情况下,才返回数据,否则不返回,修改路由:
@main.route('/register', methods=['POST'])
def register():
username = request.form['username']
password = request.form['password']
if username and password:
user = User.query.filter_by(username=username)
if user is None:
##添加进数据库
user = User(username=username)
##如果没有app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
##这句后面还要加上db.session.commit()才会提交到数据库
db.session.add(user)
session['known'] = False
else:
session['known'] = True
session['username'] = username
session['password'] = password
username=session.get('username')
password = session.get('password')
return json.dumps({
'username': username,
'password': password
})
else:
return '请输入正确的账号密码'
return Json.dumps 返回了一个json数据,记得import json
教程下一步是判断用户是否登陆(选择进入登陆页还是主页),这里我把这个判断放到前端,前端传给后台用户名和密码,后台给一个token,前端保存token,用户退出则清除token
基于token的用户认证
- 添加生成token和验证token的方法,models.py:
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def generate_auth_token(self, expiration = 600):
s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
return s.dumps({ 'id': self.id })
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
user = User.query.get(data['id'])
return user