密码保护

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, render_template, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
import config
from functools import wraps
from datetime import datetime
from sqlalchemy import or_, and_
from werkzeug.security import generate_password_hash,check_password_hash

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)


class User(db.Model):  # 创建类User
    __tablename__ = 'user'  # 类对应的表名user
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # autoincrement自增长
    username = db.Column(db.String(20), nullable=False)  # nullable是否为空
    _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 Fabu(db.Model):
    __tablename__ = 'fabu'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    detail = db.Column(db.Text, nullable=False)
    creat_time = db.Column(db.DateTime, default=datetime.now)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', backref=db.backref('fabu'))

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'))
    fabu_id = db.Column(db.Integer, db.ForeignKey('fabu.id'))
    creat_time = db.Column(db.DateTime, default=datetime.now)
    detail = db.Column(db.Text, nullable=False)
    fabu = db.relationship('Fabu',backref=db.backref('comments',order_by=creat_time.desc))
    author = db.relationship('User', backref=db.backref('comments'))



db.create_all()





@app.route('/')
def daohang():

    context={
        'fabus': Fabu.query.order_by('-creat_time').all()

    }
    return render_template('daohang.html',**context)


@app.route('/denglu/', methods=['GET', 'POST'])
def denglu():
    if request.method == 'GET':
        return render_template('denglu.html')
    else:
        username = request.form.get('user')  # post请求模式,安排对象接收数据
        password = request.form.get('pass')
        user = User.query.filter(User.username == username).first()  # 作查询,并判断
        if user:  # 判断用户名
            if user.check_password(password):# 判断密码
                session['user'] = username  # 利用session添加传回来的值username
                session.permanent = True  # 设置session过期的时间
                return redirect(url_for('daohang'))
            else:
                return u'用户密码错误'
        else:
            return u'用户不存在,请先注册'


@app.context_processor
def mycontext():
    user = session.get('user')
    if user:
        return {'username': user}  # 包装到username,在所有html模板中可调用
    else:
        return {}  # 返回空字典,因为返回结果必须是dict



@app.route('/logout')
def logout():
    session.clear()   #注销时删除所有session
    return redirect(url_for('daohang'))



@app.route('/zhuce/', methods=['GET', 'POST'])
def zhuce():
    if request.method == 'GET':
        return render_template('zhuce.html')
    else:
        username = request.form.get('user')  # post请求模式,安排对象接收数据
        password = request.form.get('pass')
        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)  # 将对象接收的数据赋到User类中,即存到数据库
            db.session.add(user)  # 执行操作
            db.session.commit()
            return redirect(url_for('denglu'))  # redirect重定向


def loginFirst(fabu):
    @wraps(fabu)  # 加上wraps,它可以保留原有函数的__name__,docstring
    def wrapper(*args, **kwargs):  # 定义wrapper函数将其返回,用*args, **kwargs把原函数的参数进行传递
        if session.get('user'):  # 只有经过登陆,session才能记住并get到值
            return fabu(*args, **kwargs)
        else:
            return redirect(url_for('denglu'))

    return wrapper



@app.route('/tupian/')
def tupian():
    return render_template('tupian.html')



@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
        fabu = Fabu(title=title, detail=detail, author_id=author_id)
        db.session.add(fabu)
        db.session.commit()
        return redirect(url_for('daohang'))



@app.route('/detail/<question_id>')
def detail(question_id):
    quest=Fabu.query.filter(Fabu.id==question_id).first()
    comments = Comment.query.filter(Comment.fabu_id == question_id).all()
    return render_template('fabu_view.html',ques=quest,comments=comments)



@app.route('/comment/',methods=['POST'])
@loginFirst
def comment():
    detail = request.form.get('pinglun')
    author_id = User.query.filter(User.username == session.get('user')).first().id
    fabu_id = request.form.get('hidden_id')
    comment = Comment(detail=detail,author_id=author_id,fabu_id=fabu_id)
    db.session.add(comment)  # 执行操作
    db.session.commit()  # 提交到数据库
    return redirect(url_for('detail',question_id=fabu_id))



@app.route('/usercenter/<user_id>/<tag>')
@loginFirst
def usercenter(user_id,tag):
    user=User.query.filter(User.id==user_id).first()
    context={
        'user_id':user.id,
        'username': user.username,
        'fabus': user.fabu,
        'comments': user.comments
    }
    if tag=='1':
        return render_template('usercenter1.html',**context)
    elif tag=='2':
        return render_template('usercenter2.html', **context)
    else:
        return render_template('usercenter3.html', **context)

@app.route('/search/')
def search():
    qu = request.args.get('q')
    ques = Fabu.query.filter(
        or_(
            Fabu.title.contains(qu),
            Fabu.detail.contains(qu)
        )
    ).order_by('-creat_time')
    return render_template('daohang.html', fabus=ques)

if __name__ == '__main__':
    app.run(debug=True)

 

posted on 2017-12-22 20:59  137陈楚洪  阅读(243)  评论(0编辑  收藏  举报

导航