Flask(11)-博客文章

提交显示博客文章

  • 创建文章模型Post
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')

class User(Usermixin, db.Model):
    posts = db.relationship('Post', backref='author', lazy='dynamic')
  • 文章博客表单PostForm
  • 处理文章博客的首页路由route(‘/’)
@main.route('/', methods=['GET', 'POST'])
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) 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)
    #关键在于index模板中如何排列posts

?? 数据库需要真正的用户对象,因此要调用 _get_current_object() 方法。

  • 显示博客文章的首页模板
{{ quick_form(form) }}

{% for post in posts %}
    <a href="{{ url_for('.user', username=post.author.username) }}">
        <img src="{{ post.author.gravatar(size=40) }}">
# 将图像作为链接
    </a>
    {{ moment(post.timestamp).fromNow() }}
    <a href="{{ url_for('.user', username=post.author.username) }}">
        {{ post.author.username }}
# 将名字作为链接
    </a>
    {{ post.body }}
{% endfor %}

在资料页显示博客

  • 路由route(‘/user/<username>’)
  • 修改user.html模板(将显示文章的代码独立出来为_posts.html模板)
{% include '_posts.html' %}
...

分页显示博客文章

  • 创建虚拟文章
  • 对首页路由修改
def index():
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=10, error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts, pagination=pagination)

posted @   影随风动91  阅读(9)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示