喃喃治愈你博客项目文档
主要功能代码如下:
from flask import Flask from flask import render_template, request, redirect, url_for, session import config, os from functools import wraps from datetime import datetime from flask_sqlalchemy import SQLAlchemy 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) # 收藏表 Collection = db.Table( 'collection', db.Column('id', db.Integer, primary_key=True, autoincrement=True), db.Column('book_id', db.Integer, db.ForeignKey('question.id')), # 评论对应的文章的id db.Column('collection', db.Integer, db.ForeignKey('user.id')), # 收藏用户的id db.Column('createdate', db.DATETIME) # 发布时间 ) class User(db.Model): __tablename__ = 'user' # 建立一个表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) say = db.Column(db.String(50)) icon = db.Column(db.String(50)) collection = db.relationship('Question', secondary=Collection, backref=db.backref('user', lazy='dynamic'), lazy='dynamic') @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): return check_password_hash(self._password, row_password) 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')) creat_time = db.Column(db.DateTime, default=datetime.now()) detail = db.Column(db.TEXT, nullable=False) question = db.relationship('Question', backref=db.backref('comment')) author = db.relationship('User', backref=db.backref('comment', order_by=creat_time.desc)) class Question(db.Model): __tablename__ = 'question' 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')) cf = db.Column(db.Integer, db.ForeignKey('cf.id')) look = db.Column(db.Integer) click = db.Column(db.Integer) author = db.relationship('User', backref=db.backref('question')) cfClass = db.relationship('Cf', backref=db.backref('question')) # 分类 class Cf(db.Model): __tablname__ = 'cf' id = db.Column(db.Integer, primary_key=True, autoincrement=True) # 数据库唯识别id name = db.Column(db.String(30)) # 文章名称 context = db.Column(db.TEXT) # 分类内容 db.create_all() # 退出 @app.route('/logout/') def logout(): session.pop('username') return redirect(url_for('index')) # 上下文 @app.context_processor def myContext(): username = session.get('username') if username: user = User.query.filter(User.username == username).first() else: user = {} if user: return {'user_id': user.id, 'user': user} else: return {} # 登陆 @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['username'] = user.username session['user_id'] = user.id session.permanent = True # 重新定位到首页 return redirect(url_for('index')) else: # 重新定位到注册 return redirect(url_for('login')) else: return redirect(url_for('login')) # 注册 @app.route('/regist/', methods=['GET', 'POST']) def regist(): if request.method == 'GET': # 打开注册页的模板 return render_template('regist.html') else: # 收到用户上传的信息 username = request.form.get('username') password = request.form.get('password') user = User.query.filter(User.username == username).first() if user: return 'error:user exitst' else: user = User(username=username, password=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('username'): return func(*args, **kwargs) else: return redirect(url_for('login')) # 返回一个函数 return wrapper @app.route('/setPassword/<id>', methods=['GET', 'POST']) @loginFirst def setPassword(id): if request.method == 'GET': return render_template('setPassword.html') else: user = User.query.filter(User.id == id).first() if user: if user.check_password(request.form.get('old')): user.password = request.form.get('new1') db.session.commit() info = '修改成功' else: info = '原密码错误' else: info = '未知错误' return redirect(url_for('index', info=info)) # 发布问答 @app.route('/question', methods=['GET', 'POST']) @loginFirst def question(): if request.method == 'GET': cf = Cf.query.all() return render_template('question.html', cf=cf) else: title = request.form.get('title') detail = request.form.get('detail') author_id = request.form.get('author_id') cf = request.form.get('cf') question = Question(title=title, detail=detail, author_id=author_id, cf=cf) db.session.add(question) # 加入数据库 db.session.commit() return redirect(url_for('index')) # 上传头像 @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.icon = 'uploads/' + f.filename db.session.commit() return redirect(url_for('setPassword', id=user_id)); # 发布评论 @app.route('/answer/', methods=['GET', 'POST']) def answer(): if request.method == 'POST': question_id = request.form.get('question_id') author_id = request.form.get('author_id') detail = request.form.get('detail') comment = Comment(question_id=question_id, author_id=author_id, detail=detail) db.session.add(comment) db.session.commit() return redirect(url_for('detail', question_id=question_id)) # 某用户发布过的所有评论 @app.route('/commentaries/<user_id>') def commentaries(user_id): userCommentaries = Comment.query.filter(Comment.answer_id == user_id).all() num = len(userCommentaries) id = session.get('user_id') if id: user = User.query.filter(User.id == id).first() else: user = {} return render_template('commentaries.html', userCommentaries=userCommentaries, user=user, num=num) # 首页 @app.route('/') def index(): if request.args.get('info'): info = request.args.get('info') else: info = None; context = { 'questions': Question.query.order_by('-creat_time').all(), 'cf': Cf.query.all(), 'info': info, 'hot': Question.query.order_by('-click').all()[0:5] } return render_template('index.html', **context) # 某用户发布过的所有评论 @app.route('/comment/<user_id>/<num>') def comment(user_id, num): user = User.query.filter(User.id == user_id).first() content = { 'comment': user.comment, 'questions': user.question, 'user2': user, } if (num == '1'): return render_template('subComment1.html', **content, title='全部问题') elif (num == '2'): return render_template('subComment2.html', **content) elif (num == '3'): return render_template('subComment3.html', **content) elif (num == '4'): content = { 'comment': user.comment, 'questions': user.collection.all(), 'user2': user, } return render_template('subComment1.html', **content, title='我的收藏') else: return render_template('subComment1.html', **content) @app.route('/c/<cf>') def c(cf): content = { 'questions': Question.query.filter(Question.cf == cf).order_by('-creat_time').all(), 'cf': Cf.query.all(), 'hot': Question.query.order_by('-click').all()[0:5] } return render_template('index.html', **content) # 详情页 @app.route('/detail/<question_id>', methods=['GET', 'POST']) @loginFirst def detail(question_id): quest = Question.query.filter(Question.id == question_id).first() u = User.query.filter(User.id == session.get('user_id')).first() if request.method == 'POST': if request.form.get('click') == '1': quest.click = quest.click + 1 if request.form.get('collection') == '1': user = u user.collection.append(quest) db.session.add(user) col = u.collection.filter_by(id=question_id).first() if col is None: col = {} comment = Comment.query.filter(Comment.question_id == question_id).order_by('-creat_time').all() quest.look = quest.look + 1 content = { 'ques': quest, 'comment': comment, 'col': col, 'questions': Question.query.filter(Question.cf == quest.cf).all(), } return render_template('detail.html', **content) # 模糊查找 @app.route('/search') def search(): qu = request.args.get('q') c = '' if request.args.get('c') == '' else request.args.get('c') y = '' if request.args.get('y') == '' else request.args.get('y') query = Question.query.filter( or_( Question.title.contains(qu), Question.detail.contains(qu), ), Question.cf.like('%' + c + '%'), Question.creat_time.like('%' + y + '%'), ).order_by('-creat_time').all() context = { 'questions': query, 'cf': Cf.query.all(), 'hot': Question.query.order_by('-click').all()[0:5] } return render_template('index.html', **context) if __name__ == '__main__': app.run()