1.更新User对象,设置对内的_password
class User(db.Model):
__tablename__ = ‘user‘
_password = db.Column(db.String(200), nullable=False) #内部使用
2.编写对外的password
from werkzeug.security import generate_password_hash, check_password_hash
@property
def password(self): #外部使用,取值
return self._password
@password.setter
def password(self, row_password):#外部使用,赋值
self._password = generate_password_hash(row_password)
3.密码验证的方法:
def check_password(self, row_password): #密码验证
result = check_password_hash(self._password,row_password)
return result
4.登录验证:
password1 = request.form.get(‘password‘)
user = User.query.filter(User.username == username).first()
if user:
if user.check_password(password1):
from flask import Flask from flask import render_template, request, redirect, url_for, session from functools import wraps from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash import config,os from sqlalchemy import or_,and_ from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class User(db.Model): __tablename__=‘user‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(20), nullable=False) _password = db.Column(db.String(200), nullable=False)#内部使用 nickname = db.Column(db.String(20), nullable=True) @property def password(self): #外部使用 return self._password @password.setter def password(self,row_password): self._password = generate_password_hash(row_password) def check_password(self,row_password): result = check_password_hash(self._password,row_password) return result class Ques(db.Model): __tablename__=‘question‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) author_id = db.Column(db.Integer, db.ForeignKey(‘user.id‘)) author = db.relationship(‘User‘, backref=db.backref(‘question‘)) title = db.Column(db.String(20), nullable=False) detail = db.Column(db.Text, nullable=False) create_time = db.Column(db.DateTime, default=datetime.now) class Comment(db.Model): __tablename__ = ‘comment‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) author_id = db.Column(db.Integer, db.ForeignKey(‘user.id‘)) question_id = db.Column(db.Integer, db.ForeignKey(‘question.id‘)) question = db.relationship(‘Ques‘, backref=db.backref(‘comment‘)) author = db.relationship(‘User‘, backref=db.backref(‘comment‘)) detail = db.Column(db.Text, nullable=False) create_time = db.Column(db.DateTime, default=datetime.now) db.create_all() @app.route(‘/‘) def index(): context={ ‘question‘:Ques.query.all() } return render_template(‘index.html‘,**context) @app.route(‘/login‘,methods=[‘GET‘,‘POST‘]) def login(): if request.method == ‘GET‘: return render_template(‘login.html‘) else: username = request.form.get(‘username‘) password1 = request.form.get(‘password‘) user = User.query.filter(User.username == username).first() # 判断用户名是否存在 if user: if user.check_password(password1): session[‘user‘] = username session[‘userid‘]=user.id session.permanent = True return redirect(url_for(‘index‘)) else: return u‘密码错误‘ else: return u‘账号不存在‘ @app.context_processor def context(): username=session.get(‘user‘) if username: return {‘username‘: username} else: return {} @app.route(‘/loginout‘) def loginout(): session.clear() return redirect(url_for(‘index‘)) @app.route(‘/register‘,methods=[‘GET‘,‘POST‘]) def register(): if request.method == ‘GET‘: return render_template(‘register.html‘) else: username = request.form.get(‘username‘) password = request.form.get(‘password‘) nickname=request.form.get(‘nickname‘) user = User.query.filter(User.username == username).first() # 判断用户名是否存在 if user: return u‘账号已存在‘ else: user = User(username=username, password=password,nickname=nickname) db.session.add(user) db.session.commit() return redirect(url_for(‘login‘)) def loginFirst(func): #参数是函数 @wraps(func) def wrapper(*args, **kwargs): #定义个函数将其返回 if session.get(‘user‘): return func(*args, **kwargs) else: return redirect(url_for(‘login‘)) # print(‘call %s():‘ % func.__name__) # return func(*args, ** kwargs) return wrapper #返回一个函数 @app.route(‘/fabu‘,methods=[‘GET‘,‘POST‘]) @loginFirst def fabu(): if request.method == ‘GET‘: return render_template(‘fabu.html‘) else: title = request.form.get(‘title‘) detail = request.form.get(‘detail‘) author_id = User.query.filter(User.username == session.get(‘user‘)).first().id # 判断用户名是否存在 question = Ques(title=title, detail=detail, author_id=author_id) db.session.add(question) db.session.commit() return redirect(url_for(‘index‘)) @app.route(‘/detail/<question_id>‘,methods=[‘GET‘,‘POST‘]) def detail(question_id): quest = Ques.query.filter(Ques.id == question_id).first() comments= Comment.query.filter(Comment.question_id == question_id).all() return render_template(‘detail.html‘,quest=quest,comments=comments) @app.route(‘/comment‘,methods=[‘GET‘,‘POST‘]) @loginFirst def comment(): comment = request.form.get(‘detail‘) auth_id = User.query.filter(User.username == session.get(‘user‘)).first().id # 判断用户名是否存在 question_id = Ques.query.filter(User.username == session.get(‘user‘)).first().id comm = Comment(author_id=auth_id, question_id=question_id, detail=comment) db.session.add(comm) db.session.commit() return redirect(url_for(‘detail‘,question_id=question_id)) @app.route(‘/usercenter/<user_id>/<tag>‘,methods=[‘GET‘,‘POST‘]) @loginFirst def usercenter(user_id,tag): user = User.query.filter(User.id == user_id).first() context = { ‘username_id‘: user.id, ‘username‘: user.username, ‘questions‘: user.question, ‘comments‘: user.comment } if tag == ‘1‘: return render_template(‘usercenter.html‘, **context) elif tag == ‘2‘: return render_template(‘all_question.html‘, **context) else: return render_template(‘all_comment.html‘, **context) @app.route(‘/search/‘,methods=[‘GET‘,‘POST‘]) def search(): search = request.args.get(‘search‘) question = Ques.query.filter( or_( Ques.title.contains(search), Ques.detail.contains(search) ) ).order_by(‘-create_time‘) return render_template(‘index.html‘,question=question) if __name__ == ‘__main__‘: app.run(debug=True)