Flask(11)-博客文章

来源:互联网 发布:form表单提交数据加密 编辑:程序博客网 时间:2024/05/16 22:24

提交显示博客文章

  • 创建文章模型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)
0 0
原创粉丝点击