密碼保護

1.更新User對象,設置對內的_passwordhtml

class User(db.Model):sql

    __tablename__ = 'user' 數據庫

    _password = db.Column(db.String(200), nullable=False) #內部使用flask

 

2.編寫對外的passwordsession

from werkzeug.security import generate_password_hash, check_password_hashapp

    @property函數

    def password(self):  #外部使用,取值url

        return self._password

spa

    @password.setterdebug

    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
from sqlalchemy import or_,and_
from functools import wraps
from hashlib import md5
import os
import congif

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

# 用戶信息
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.String(17), primary_key=True)  # 數據庫惟識別id
    name = db.Column(db.String(20), nullable=False)  # 登陸帳號名
    title = db.Column(db.String(30))  # 顯示名稱
    password = db.Column(db.String(42), nullable=False)  # 密碼
    truename = db.Column(db.String(10))  # 真實姓名
    sex = db.Column(db.String(1), default='0')  # 性別
    phone = db.Column(db.String(11))  # 電話號碼
    email = db.Column(db.String(40))  # 郵箱
    logo = db.Column(db.String(50))  # 頭像
    qq = db.Column(db.String(11))  # qq號碼
    createdate = db.Column(db.DATETIME)  # 註冊日期
    level = db.Column(db.String(2))  # 用戶等級
    address = db.Column(db.String(60))  # 用戶住址

# 圖書分類 classification(id,name,content)
class Classification(db.Model):
    __tablname__ = 'classification'
    id = db.Column(db.String(17), primary_key=True)  # 數據庫惟識別id
    name = db.Column(db.String(30))  # 文章名稱
    logo = db.Column(db.String(50))  # 頭像地址
    context = db.Column(db.TEXT)  # 分類內容

# book(id,title,abstracts,content,createdate,author_id,size,chilk,disc,classification)
# 發佈圖書及問答
class Book(db.Model):
    __tablname__ = 'book'
    id = db.Column(db.String(17), primary_key=True)  # 數據庫惟識別id
    title = db.Column(db.String(30))  # 文章標題
    abstracts = db.Column(db.String(150))  # 文章摘要
    content = db.Column(db.TEXT)  # 文章內容
    createdate = db.Column(db.DATETIME)  # 發佈時間
    author_id = db.Column(db.String(17), db.ForeignKey('user.id'))  # 發佈者id
    size = db.Column(db.String(30))  # 文章長度
    chilk = db.Column(db.Integer())  # 閱讀數
    disc = db.Column(db.Integer())   #點贊數
    classification = db.Column(db.String(17), db.ForeignKey('classification.id'))  # 文章分類id
    authorClass = db.relationship('User', backref=db.backref('book'))
    classificationClass = db.relationship('Classification', backref=db.backref('book'))

# 評論表
class Commentaries(db.Model):
    __tablname__ = 'commentaries'
    id = db.Column(db.String(17), primary_key=True)  # 數據庫惟一識別id
    book_id = db.Column(db.String(17), db.ForeignKey('book.id'))  # 評論對應的文章的id
    question_id = db.Column(db.String(17))  # 問題的提出者id,或者是文章做者id
    answer_id = db.Column(db.String(17), db.ForeignKey('user.id'))  # 回答問題用戶的id
    date = db.Column(db.DATETIME)  # 回答日期
    content = db.Column(db.TEXT)  # 回答內容
    answer = db.relationship('User', backref=db.backref('commentaries'))
    book = db.relationship('Book', backref=db.backref('commentaries',order_by=date.desc))

# db.create_all()
# 增長一條數據
# user = User(name = 'xiao',password = '123')
# db.session.add(user)
# db.session.commit()

# 查詢一條數據
# user = User.query.filter(User.name=='xiao').first()
# print(user.name,user.password)

# 更改一條數據
# user = User.query.filter(User.name=='xiao').first()
# user.password = 'xxx'
# db.session.commit()

# 刪除一條數據
# user = User.query.filter(User.name=='xiao').first()
# db.session.delete(user)
# db.session.commit()

# 退出登陸
@app.route('/logout/')
def logout():
    session.pop('user_id')
    session.pop('title')
    return redirect(url_for('index'))

# 登陸
@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_name = request.form.get('user_name')
        user_password = request.form.get('user_password')
        user = User.query.filter(User.name == user_name,
                                 User.password == md5(user_password.encode("utf-8")).hexdigest()).first()
        if user:
            session['user_id'] = user.id
            session['title'] = user.title
            session.permanent = True
            poi = request.args.get('poi')
            if poi:
                return redirect(url_for('poi', book_id=poi))
            return redirect(url_for('index'))
        else:
            return redirect(url_for('login'))
    else:
        return render_template('login.html')

# 上下文處理器
@app.context_processor
def myContext():
    id = session.get('user_id')
    title = session.get('title')
    if id:
        user = User.query.filter(User.id == id).first()
    else:
        user = {}
    if title:
        return {'title': title, 'user_id': id, 'user': user}
    else:
        return {}

# 註冊
@app.route('/regist/', methods=['GET', 'POST'])
def regist():
    if request.method == 'GET':
        user_name = request.args.get('user_name')
        if user_name:
            user = User.query.filter(User.name == user_name).first()
            if user:
                return '用戶已存在'
            else:
                return 'ok'
        else:
            return render_template('regist.html')
    else:
        user_name = request.form.get('user_name')
        user_title = request.form.get('user_title')
        user_password = request.form.get('user_password')
        user = User.query.filter(User.name == user_name).first()
        if user:
            return 'error:user exitst'
        else:
            user = User(id="1", name=user_name, title=user_title, password=user_password)
            db.session.add(user)  # 加入數據庫
            db.session.commit()
            return redirect(url_for('login'))

# 定義一個裝飾器出驗證用戶有是不是登錄
# 定義一個參數函數
def loginFirst(func):
    # 定義一個函數將其返回
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('title'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))

    # 返回一個函數
    return wrapper

# 發佈問答
@app.route('/question', methods=['GET', 'POST'])
@loginFirst
def question():
    if request.method == 'GET':
        classfly = Classification.query.all()
        context = {
            'classfly' : classfly
        }
        return render_template('question.html',**context)
    else:
        book_title = request.form.get('title')
        book_content = request.form.get('content')
        abstracts = request.form.get('abstracts')
        classification = request.form.get('classification')
        user_id = request.form.get('user_id')
        size = request.form.get('size')
        book = Book(id='1', title=book_title, abstracts=abstracts, content=book_content, author_id=user_id,classification=classification,size=size)
        db.session.add(book)  # 加入數據庫
        db.session.commit()
        return 'true'

# 詳情頁面
@app.route('/poi/<book_id>')
def poi(book_id):
    book = Book.query.filter(Book.id == book_id).first()
    answer = len(Commentaries.query.filter(Commentaries.book_id==book_id).all())
    book.chilk = book.chilk+1
    db.session.commit()
    id = session.get('user_id')
    if id:
        user = User.query.filter(User.id == id).first()
    else:
        user = {}
    return render_template('poi.html', book=book, user=user,answer=answer)

# 點贊
@app.route('/disc/')
def disc():
    book_id = request.args.get('book_id')
    book = Book.query.filter(Book.id == book_id).first()
    book.disc = book.disc+1
    db.session.commit()
    return str(book.disc)

# 發佈評論
@app.route('/answer/', methods=['GET', 'POST'])
def answer():
    if request.method == 'POST':
        book_id = request.form.get('book_id')
        question_id = request.form.get('question_id')
        answer_id = request.form.get('answer_id')
        content = request.form.get('content')
        commentaries = Commentaries(id='1', book_id=book_id, question_id=question_id, answer_id=answer_id,
                                    content=content)
        db.session.add(commentaries)
        db.session.commit()
        commentaries = Commentaries.query.filter(Commentaries.book_id == book_id).order_by('-date').all()
        context = {
            'commentaries': commentaries,
        }
        return render_template('answer.html', **context)
    else:
        book_id = request.args.get('book_id')
        commentaries = Commentaries.query.filter(Commentaries.book_id == book_id).order_by('-date').all()
        context = {
            'commentaries': commentaries,
        }
        return render_template('answer.html', **context)

# 某用戶發佈過的全部評論
@app.route('/commentaries/<user_id>',methods=['GET','POST'])
def commentaries(user_id):
    user = User.query.filter(User.id == user_id).first()
    content = {
        'userCommentaries':user.commentaries,
        'books':user.book,
        'num': len(user.commentaries),
        'user2':user
    }
    return render_template('commentaries.html', **content)

# 設置中心
@app.route('/config/<user_id>',methods=['GET','POST'])
@loginFirst
def config(user_id):
    user = User.query.filter(User.id == user_id).first()
    if request.method == 'GET':
        return render_template('config.html')
    else:
        user.title = request.form.get('title')
        user.truename = request.form.get('truename')
        user.sex = request.form.get('sex')
        user.qq = request.form.get('qq')
        user.phone = request.form.get('phone')
        user.email = request.form.get('email')
        user.address = request.form.get('address')
        db.session.commit()
        return render_template('config.html')

# 上傳頭像
@app.route('/uploadLogo/<user_id>',methods=['GET','POST'])
def uploadLogo(user_id):
    user = User.query.filter(User.id == user_id).first()
    f = request.files['logo']
    basepath = os.path.dirname(__file__)  # 當前文件所在路徑
    upload_path = os.path.join(basepath, 'static/uploads', f.filename)  # 注意:沒有的文件夾必定要先建立,否則會提示沒有該路徑
    f.save(upload_path)
    user.logo = 'uploads/'+f.filename
    db.session.commit()
    return '{"url":"'+url_for('static',filename='uploads/'+f.filename)+'"}';

# 分類列表
@app.route('/classflyList/')
def classflyList():
    classfly = Classification.query.all()
    context = {
        'classfly':classfly
    }
    return render_template('classflyList.html',**context)

# 某個分類下的文章
@app.route('/classfly/<classification_id>')
def classfly(classification_id):
    classflyList = Classification.query.all()
    classfly = Classification.query.filter(Classification.id == classification_id).first()
    context = {
        'classfly': classfly,
        'books':classfly.book,
        'classflyList': classflyList
    }
    return render_template('classfly.html',**context)

# 改密碼
@app.route('/resetPassword/<user_id>', methods=['GET', 'POST'])
@loginFirst
def resetPassword(user_id):
    user = User.query.filter(User.id == user_id).first()
    if request.method == 'GET':
        return render_template('resetPassword.html')
    else:
        password = request.form.get('password')
        oldPassword = request.form.get('oldPassword')
        if(md5(oldPassword.encode("utf-8")).hexdigest()==user.password):
            user.password = md5(password.encode("utf-8")).hexdigest()
            db.session.commit()
        else:
            return '原密碼有誤';
        return render_template('resetPassword.html')

# 模糊查找
@app.route('/search', methods=['GET', 'POST'])
def search():
    qu = request.args.get('q')
    query = Book.query.filter(
        or_(
            Book.title.contains(qu),
            Book.content.contains(qu),
        )
     ).order_by('-createdate').all()
    classfly = Classification.query.all()
    context = {
        'books': query,
        'classfly':classfly
    }
    return render_template('home.html', **context)


# 首頁
@app.route('/', methods=['GET', 'POST'])
def index():
    # context = {
    #     'userName' : "AllianceHacker",
    #     'toTime' : '11小時前',
    #     'title' : 'PHP是世界是最好的語言',
    #     'context' : 'PHP是世界是最好的語言,這是一個不須要有疑問的問題,誰不服能夠來戰啊!!!'
    # }
    books = Book.query.order_by('-createdate').all()
    classfly = Classification.query.all()
    context = {
        'books': books,
        'classfly':classfly
    }
    return render_template('home.html', **context)

#  主函數
if __name__ == '__main__':
    app.run(debug=True)

 

 

 

 

相關文章
相關標籤/搜索