完成评论功能

Posted loe05

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了完成评论功能相关的知识,希望对你有一定的参考价值。

  1. 定义评论的视图函数
    @app.route(‘/comment/‘,methods=[‘POST‘])
    def comment():
    读取前端页面数据,保存到数据库中
  2. 用<input type="hidden" 方法获取前端的"question_id" 
  3. 显示评论次数
  4. 要求评论前登录
  5. 尝试实现详情页面下的评论列表显示
  6. 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
    
    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(20), nullable=False)
    
    
    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‘))
        author = db.relationship(‘User‘, backref=db.backref(‘question‘))
    
    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(‘comments‘))
        author=db.relationship(‘User‘,backref=db.backref(‘comments‘))
    
    
    db.create_all()
    
    
    @app.route(‘/‘)
    def daohang():
        context={
            ‘questions‘:Question.query.order_by(‘creat_time‘).all()
        }
        return render_template(‘index.html‘,**context)
    
    @app.route(‘/detail/<question_id>‘,methods=[‘GET‘,‘POST‘])
    def detail(question_id):
        quest=Question.query.filter(Question.id == question_id).first()
        return render_template(‘detail.html‘,ques=quest)
    
    
    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(‘/comment/‘,methods=[‘POST‘])
    @loginFirst
    def comment():
        comment=request.form.get(‘new_comment‘)
        ques_id=request.form.get(‘question_id‘)
        auth_id=User.query.filter(User.username==session.get(‘user‘)).first().id
        comm=Comment(author_id=auth_id,question_id=ques_id,detail=comment)
        db.session.add(comm)
        db.session.commit()
        return redirect(url_for(‘detail‘,question_id=ques_id))
    
    
    
    
    @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, User.password == password).first()
            if user:
                session[‘user‘] = username
                session.permanent = True
                return redirect(url_for(‘daohang‘))
            else:
                return ‘error username or password‘
    
    
    
    @app.context_processor
    def mycontext():
        usern = session.get(‘user‘)
        if usern:
            return {‘username‘: usern}
        else:
            return {}
    
    
    @app.route(‘/logout/‘)
    def logout():
        session.clear()
        return redirect(url_for(‘regist‘))
    
    
    @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 ‘username existed‘
            else:
                user = User(username=username, password=password)
                db.session.add(user)
                db.session.commit()
                return redirect(url_for(‘login‘))
    
    
    
    
    
    @app.route(‘/question/‘, methods=[‘GET‘, ‘POST‘])
    @loginFirst
    def question():
        if request.method == ‘GET‘:
            return render_template(‘question.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 = Question(title=title, detail=detail, author_id=author_id)
            db.session.add(question)
            db.session.commit()
            return redirect(url_for(‘daohang‘))
    
    if __name__ == ‘__main__‘:
        app.run(debug=True)
    {% extends ‘daohang.html‘ %}
    {% block title %}问答详情{% endblock %}
    
    {% block main %}
        <div class="page-header">
            <h3>Title {{ ques.title }}<br><small>{{ ques.author.username }} <span class="badge">{{ ques.creat_time }}</span></small>></h3>
        </div>
        <p class="lead">detail{{ ques.detail }}</p>
        <hr>
    
        <form action="{{ url_for(‘comment‘) }}"method="post" style="...">
            <div class="form-group">
                <textarea name="new_comment" id="new-comment" class="form-control" rows="3"
                          placeholder="write your comment"></textarea>
                <input type="hidden" name="question_id" value="{{ ques.id }}">
            </div>
            <button type="submit" class="btn btn-default">发送</button>
        </form>
        <h4>评论:({{ ques.comments|length }})</h4>>
        <ul class="list-group" style="margin:10px"></ul>>
    {% endblock %}

     

以上是关于完成评论功能的主要内容,如果未能解决你的问题,请参考以下文章

解决方案电影标题中缺少代码的片段,完成挑战更多[关闭]

从零开始配置vim(27)——代码片段

从零开始配置vim(27)——代码片段

从零开始配置vim(27)——代码片段

完成评论功能

完成评论功能