1.主PY文件写视图函数,带id参数。 

@app.route('/detail/<question_id>')
def detail(question_id):
    quest = 
    return render_template('detail.html', ques = quest) 

 

2.首页标题的标签做带参数的链接。

      {{ url_for('detail',question_id = foo.id) }}

3.在详情页将数据的显示在恰当的位置。 

{{ ques.title}}
{{ ques.id  }}{{  ques.creat_time }}
{{ ques.author.username }} 
{{ ques.detail }}

 

4.建立评论的对象关系映射:

      class Comment(db.Model):

      __tablename__='comment'

5尝试实现发布评论。

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

# db.create_all()

@app.route('/')
def home():
    context={
        'questions': Question.query.all()
    }
    return render_template('home.html',**context)

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


@app.route('/comment/',methods=['POST'])
# @login_re
def comment():
        user = User.query.filter(User.username == session.get('user')).first()
        author_id = user.id
        question = Question.query.filter(Question.author_id == author_id ).first()
        question_id = question.id
        comment = Comment(author_id=author_id,question_id=question_id,detail=detail)
        db.session.add(comment)  # 保存到数据库
        db.session.commit()  # 提交
        return redirect(url_for('home'))

# @app.route('/usercenter/<user_id>')
# @login_re
# def usercenter(user_id):
#     user=User.query.filter(User.id==user_id).first()
#     context={
#         'questions':user.questions,
#         'comments':user.comments
#     }
#     return render_template('',**context)

# 显示登录的用户名
@app.context_processor
def mycontext():
    usern=session.get('user')
    if usern:
        return {'username':usern}
    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.password==password:
                session['user'] = username
                session.permanent = True
                return redirect(url_for('home'))
            else:
                return 'Password error'
        else:
            return 'Username inexistent'

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

@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:
            user1 = User(username=username, password=password)
            db.session.add(user1)
            db.session.commit()
            return redirect(url_for('login'))

# 登录装饰器
def loginFrist(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'])
@loginFrist
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        detail = request.form.get('detail')
        user=User.query.filter(User.username == session.get('user')).first()
        author_id = user.id
        question = Question.query.filter(Question.title == title).first()
        if question:
            return 'Question existed'
        else:
            question1 = Question(title=title, detail=detail, author_id=author_id)
            question1.author = user
            db.session.add(question1)  # 保存到数据库
            db.session.commit()  # 提交
            return redirect(url_for('home'))


if __name__ == '__main__':
    app.run(debug=True)
{% extends 'base.html' %}

{% block title %}Detail{% endblock %}

{% block head %}
    <link href="{{ url_for('static',filename='CSS/detail.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block main %}
<div class="detail">
    <h2>{{ question.title }}</h2>
    <a href="#">{{ question.author.username }}</a>
    <span>{{ question.creat_time }}</span>
    <div class="p">
        <p>{{ question.detail }}</p>
    </div>
    <form action="{{ url_for('comment') }}" method="post">
        <textarea name="text" rows="5"></textarea><br>
        <button >发送</button>
    </form>

    <br>

    <ul>
        <p>Comment[count]</p>
        <div>
            <li>
                <img src="{{ url_for('static',filename='image/body.png') }}">
                <a href="#">username</a>
                <span>creat_time</span><br>
                <p>comment</p>
            </li>
        </div>
    </ul>
</div>
{% endblock %}

 

posted on 2017-12-06 23:32  077吴文欣  阅读(216)  评论(0编辑  收藏  举报