用 Flask 来写个轻博客 (14) — M(V)C_实现项目首页的模板

简介: 目录目录前文列表实现所需要的视图函数实现 homehtml 模板代码分析实现效果前文列表用 Flask 来写个轻博客 (1) — 创建项目 用 Flask 来写个轻博客 (2) — Hello World! 用 Flask 来写个轻博客...

目录

前文列表

用 Flask 来写个轻博客 (1) — 创建项目
用 Flask 来写个轻博客 (2) — Hello World!
用 Flask 来写个轻博客 (3) — (M)VC_连接 MySQL 和 SQLAlchemy
用 Flask 来写个轻博客 (4) — (M)VC_创建数据模型和表
用 Flask 来写个轻博客 (5) — (M)VC_SQLAlchemy 的 CRUD 详解
用 Flask 来写个轻博客 (6) — (M)VC_models 的关系(one to many)
用 Flask 来写个轻博客 (7) — (M)VC_models 的关系(many to many)
用 Flask 来写个轻博客 (8) — (M)VC_Alembic 管理数据库结构的升级和降级
用 Flask 来写个轻博客 (9) — M(V)C_Jinja 语法基础快速概览
用 Flask 来写个轻博客 (10) — M(V)C_Jinja 常用过滤器与 Flask 特殊变量及方法
用 Flask 来写个轻博客 (11) — M(V)C_创建视图函数
用 Flask 来写个轻博客 (12) — M(V)C_编写和继承 Jinja 模板
用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验

实现所需要的视图函数

  • 在开始实现首页模板之前, 我们为了调试和显示的方便, 首先伪造一些假数据:
    • fake_data.py
import random
import datetime
from uuid import uuid4

from models import db, User, Tag, Post

user = User(id=str(uuid4()), username='jmilkfan', password='fanguiju')
db.session.add(user)
db.session.commit()

user = db.session.query(User).first()
tag_one = Tag(id=str(uuid4()), name='Python')
tag_two = Tag(id=str(uuid4()), name='Flask')
tag_three = Tag(id=str(uuid4()), name='SQLALchemy')
tag_four = Tag(id=str(uuid4()), name='JMilkFan')
tag_list = [tag_one, tag_two, tag_three, tag_four]

s = "EXAMPLE TEXT"

for i in xrange(100):
    new_post = Post(id=str(uuid4()), title="Post" + str(i))
    new_post.user = user
    new_post.publish_date = datetime.datetime.now()
    new_post.text = s
    new_post.tags = random.sample(tag_list, random.randint(1, 3))
    db.session.add(new_post)

db.session.commit()

直接在 manager shell 中导入就能够执行该脚本文件:

>>> import fake_data

home.html 的视图函数之前博文中就已经记录过了,现在再将必须的视图函数代码贴出。

  • views.py
from flask import render_template
from sqlalchemy import func

from main import app
from models import db, User, Post, Tag, Comment, posts_tags


def sidebar_data():
    """Set the sidebar function."""

    # Get post of recent
    recent = db.session.query(Post).order_by(
            Post.publish_date.desc()
        ).limit(5).all()

    # Get the tags and sort by count of posts.
    top_tags = db.session.query(
            Tag, func.count(posts_tags.c.post_id).label('total')
        ).join(
            posts_tags
        ).group_by(Tag).order_by('total DESC').limit(5).all()
    return recent, top_tags


@app.route('/')
@app.route('/<int:page>')
def home(page=1):
    """View function for home page"""

    posts = Post.query.order_by(
        Post.publish_date.desc()
    ).paginate(page, 10)

    recent, top_tags = sidebar_data()

    return render_template('home.html',
                           posts=posts,
                           recent=recent,
                           top_tags=top_tags)

@app.route('/post/<string:post_id>')
def post(post_id):
    """View function for post page"""

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post.html',
                           post=post,
                           tags=tags,
                           comments=comments,
                           recent=recent,
                           top_tags=top_tags)


@app.route('/tag/<string:tag_name>')
def tag(tag_name):
    """View function for tag page"""

    # Tag.qurey() 对象才有 first_or_404(),而 db.session.query(Model) 是没有的
    tag = Tag.query.filter_by(name=tag_name).first_or_404()
    posts = tag.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('tag.html',
                           tag=tag,
                           posts=posts,
                           recent=recent,
                           top_tags=top_tags)

实现 home.html 模板

  • templates/home.html
<!-- Replace the TITLE of template base.html -->
{% extends "base.html"%}
{% block title %}JmilkFan's Blog{% endblock %}

<!-- Replace the BODY of template base.html -->
{% block body %}
<!-- The data object from view function: `home()` -->
<div class="row">
  <div class="col-lg-9">
    <!-- Get Pagination object-->
    {% for post in posts.items %}
    <div class="row">
      <div class="col-lg-12">
        <h1>{{ post.title }}</h1>
      </div>
    </div>
    <div class="row">
      <div class="col-lg-12">
        {{ post.text | truncate(255) | safe }}
        <!-- Set the link for read more -->
        <a href="{{
          url_for('post', post_id=post.id)
          }}">Read More</a>
      </div>
    </div>
    {% endfor %}
  </div>
  <div class="col-lg-3">
    <div class="row">
      <h5>Recent Posts</h5>
      <ul>
        {% for post in recent %}
        <!-- Set the link for recent posts. -->
        <li><a href="{{
          url_for('post', post_id=post.id)
          }}">{{ post.title }}</a></li>
        {% endfor %}
      </ul>
    </div>
    <div class="row">
      <h5>Popular Tags</h5>
      <ul>
        {% for tag in top_tags %}
        <li><a href="{{
          url_for('tag', tag_name=tag[0].name)
          }}">{{ tag[0].name }}</a></li>
        {% endfor %}
      </ul>
    </div>
  </div>
  <!-- Call the Macro: `render_pagination` from base.html -->
  {{ render_pagination(posts, 'home') }}
</div>
{% endblock %}

代码分析

需求:我们希望当访问到域名 http://<ipaddress>:5000/,即访问博客的 / 时,能够正文处显示文章列表,右上侧边栏显示最新的 5 篇博文,右下侧边拦显示 关联博文数最多的 5 个标签,并且希望每一个页面的右侧边栏都是一致的。

  • 按照这个需求,首先我们需要定义一个路由函数(在这里同时也是视图函数) home() 来跳转到首页,并且首页中具有分页的功能,所以会定义两个 app.oute() 装饰器。

  • 同时因为我们需要在右侧边栏显示最新的 5 篇博文和博文关联数最多的 5 个标签,所以需要提供 recent/recent 数据对象,并且这些对象是高重用的,所以将其抽象成一个函数。

  • 我们还希望能够通过右侧边拦提供的链接跳转到具体的 post 或 tag 中,这就需要得到 posts/tags 表中的数据对象,所以会使用到视图函数 post()/tag()

实现效果

这里写图片描述

  • 再结合在前面博文中实现的分页链接宏
    这里写图片描述
相关文章
|
2月前
|
数据可视化 API 开发者
通俗易懂:一步步教你 Flask 项目自动生成 API 文档
Flasgger,作为一款强大的 Flask 扩展,自动从 Flask 应用中提取并生成 OpenAPI 规范文档,配备 SwaggerUI,为开发者提供了一条快捷通道,让 API 的文档编制和交互式测试变得简单易行。Flasgger 的设计原则是简化开发流程,通过与 Flask 框架的无缝整合,让开发者可以更专注于应用逻辑的构建。
|
5月前
|
前端开发 JavaScript Python
flask 项目目录结构
flask 项目目录结构
93 0
|
7月前
|
存储 前端开发 NoSQL
项目阶段之flask(三)
项目阶段之flask(三)
|
4月前
|
前端开发 JavaScript 数据库
Flask狼书笔记 | 09_图片社交网站 - 大型项目的架构与需求(2)
9.8 收藏图片 前面已经学习过如何使用关联表来表示多对多关系,缺点是只能表示关系,不能存储数据(如我还想记录下收藏图片的时间戳)。这种情况下,我们可以使用关联模型来表示多对多关系。 在关联模型中,我们将Photo模型与User模型的多对多关系,分离成了User模型和Collect模型的一对多关系,和Photo模型与Collect模型的一对多关系。
59 0
|
10天前
|
Python
Flask中的模板的使用
Flask中的模板的使用
12 0
|
4月前
|
存储 移动开发 前端开发
Flask狼书笔记 | 03_模板
3 模板 模板(template):包含固定内容和动态部分的可重用文件。Jinja2模板引擎可用于任何纯文本文件。 3.1 模板基本使用
31 0
|
4月前
|
开发框架 Python
Web 框架 Flask 快速入门(一)flask基础与模板
🌴 Flask基础和模板 1、web框架的作用 避免重复造轮子,app程序不必关心于服务器的沟通方式,而专注于核心的业务逻辑实现。 稳定,可扩展性强
43 0
|
5月前
|
JavaScript 前端开发 知识图谱
flask-模板用法
flask-模板用法
29 0
|
7月前
|
Python
项目阶段之flask(六)
项目阶段之flask(六)
|
7月前
|
前端开发 数据安全/隐私保护 Python
项目阶段之flask(五)
项目阶段之flask(五)
项目阶段之flask(五)