密码保护

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['SECRET_KEY'] = '123456'
app.config.from_object(config)
db = SQLAlchemy(app)


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=TabError, autoincrement=True)
    username = db.Column(db.String(20), nullable=False)
    _password = db.Column(db.String(200), nullable=False)#内部使用
    # nickname = db.Column(db.String(20))

    @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 Post(db.Model):
    __tablename__ = 'post'
    id = db.Column(db.Integer, primary_key=TabError, 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('post'))


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


db.create_all()


# 查询删除
# user = User.query.filter(User.username == 'lin').first()
# db.session.delete(user)
# db.session.commit()

# 修改
# user = User.query.filter(User.username == 'lin').first()
# user.password = '1234'
# print(user.username,user.password)
# db.session.commit()

# 增加
# user = User(username = 'lin',password = 'lin')
# db.session.add(user)
# db.session.commit()




@app.route('/')
def jianshu():
    context = {
        'post': Post.query.order_by('-creat_time').all()
    }
    return render_template('jianshu.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')
        password = request.form.get('password')
        user = User.query.filter(User.username == username).first()
        if user:
            if user.check_password(password):
                session['user'] = username
                session['userid']=user.id
                session.permanent = True
                return redirect(url_for('jianshu'))
            else:
                return 'password error'
        else:
            return u'error username or password'


@app.route("/enroll/", methods=['GET', 'POST'])
def enroll():
    if request.method == 'GET':
        return render_template('enroll.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter(User.username == username).first()
        if user:
            return 'username exited'
        else:
            user = User(username=username, password=password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))


@app.route('/detail/<post_id>')
def detail(post_id):
    post = Post.query.filter(Post.id == post_id).first()
    return render_template('detail.html', pos=post)  # 页面上用pos,函数用post,传递到pos


@app.context_processor
def mycontext():
    usern = session.get('user')
    if usern:
        user=User.query.filter(User.username==usern).first()
        return {'username': usern,'user':user}
    else:
        return {}


@app.route('/logout/')
def logout():
    session.clear()
    return redirect(url_for('jianshu'))


def loginFirst(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))

    return wrapper


@app.route("/post/", methods=['GET', 'POST'])
@loginFirst
def post():
    if request.method == 'GET':
        return render_template('post.html')
    else:
        title = request.form.get('title')
        detail = request.form.get('detail')
        author_id = User.query.filter(User.username == session.get('user')).first().id
        post = Post(title=title, detail=detail, author_id=author_id)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('jianshu'))


@app.route('/comment/', methods=['POST'])
@loginFirst
def comment():
    comment = request.form.get('new_comment')
    pos_id = request.form.get('post_id')
    auth_id = User.query.filter(User.username == session.get('user')).first().id
    comm = Comment(author_id=auth_id, post_id=pos_id, detail=comment)
    db.session.add(comm)
    db.session.commit()
    return redirect(url_for('detail', post_id=pos_id))


@app.route('/username/<user_id>/<tag>')
@loginFirst
def usercenter(user_id, tag):
    user = User.query.filter(User.id == user_id).first()
    context = {
        'user': user,
        'post': user.post,
        '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')
    pos = Post.query.filter(
        or_(
            Post.title.contains(qu),
            Post.detail.contains(qu)
        )
    ).order_by('-creat_time')
    return render_template('jianshu.html', post=pos)


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

 

posted on 2017-12-22 20:46  025林婷婷  阅读(176)  评论(0编辑  收藏  举报