Post文章模型
class User(UserMixin, db.Model): # ... posts = db.relationship('Post', backref='author', lazy='dynamic') # 多文章对一用户的关系 class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
处理博客文章的首页路由
@main.route('/', methods=['GET', 'POST']) def index(): form = PostForm() if current_user.can(Permission.WRITE) and form.validate_on_submit(): post = Post(body=form.body.data, author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) posts = Post.query.order_by(Post.timestamp.desc()).all() return render_template('index.html', form=form, posts=posts)在资料页中显示博客文章
@main.route('/user/<username>') def user(username): user = User.query.filter_by(username=username).first() if user is None: # 用户不存在 abort(404) posts = user.posts.order_by(Post.timestamp.desc()).all() return render_template('user.html', user=user, posts=posts)