• 首页列表显示全部问答,完成问答详情页布局。


    1. 首页列表显示全部问答:
      1. 将数据库查询结果传递到前端页面 Question.query.all()
      2. 前端页面循环显示整个列表。
      3. 问答排序
    2. 完成问答详情页布局:
      1. 包含问答的全部信息
      2. 评论区
      3. 以往评论列表显示区。
    3. 在首页点击问答标题,链接到相应详情页。

    py:

    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'))
    
    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>')
    def detail(question_id):
        quest=Question.query.filter(Question.id == question_id).first()
    
        return render_template('detail.html',ques=quest)
    
    
    @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'))
    
    
    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('/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)

    detail.html:

    {% extends 'daohang.html' %}
    {% block title %}问答详情{% endblock %}
    
    {% block main %}
        <div class="page-header">
            <h3>Title {{ ques }}<br><small>author{{ ques.author_id }}{{ ques.create_time }}</small>></h3>
    
        </div>
        <p class="lead">detail{{ ques.detail }}</p>
        <hr>
    
        <form action="{{ url_for('question') }}"method="post" style="...">
            <div class="form-group">
                <textarea name="new_comment" id="new-comment" class="form-control" rows="3"
                          placeholder="write your comment"></textarea>
            </div>
            <button type="submit" class="btn btn-default">发送</button>
    
        </form>
        <ul class="list-group" style="margin: 10px"...></ul>>
    {% endblock %}

    index.html:

    {% extends "daohang.html" %}
    {% block title %}首页{% endblock %}
    
    {% block main %}
       <p>{{ user }}contextx</p>
    
       <ul class="list-group" style="...">
           {% for foo in questions %}
               <li class="list-group-item">
               <span class="glyphicon glyphicon-leaf" aria-hidden="true"></span>
               <a href="#">{{ foo.author.username }}</a>
               <br>
               <a href="{{ url_for('detail',question_id=foo.id) }}">{{ foo.title }}</a>
               <span class="badge">{{ foo.creat_time }}</span>
               <p style="...">{{ foo.detail }}</p>
    
               </li>
    
           {% endfor %}
       </ul>
    {% endblock %}

  • 相关阅读:
    centos 7.5 snmp 安装
    centos 7.5 telnet 离线安装
    使用httpClient发送请求(支持https)
    kafka基本概念
    List根据时间字符串排序
    mac安装yosys遇到`dyld: malformed mach-o image`报错
    ctags的--exclude选项
    每周分享(3)
    实践OKR极易出现的四大误区
    从OKR小白到成功落地OKR(三)
  • 原文地址:https://www.cnblogs.com/chenhuafei/p/7941419.html
Copyright © 2020-2023  润新知