07-文章展示页

  • 阅读: 363
  • 更新: 2022-04-30

1. 表结构

首先需要设计文章在数据库中的表结构,表名为 article,设计如下:

字段 类型 描述
title string 文章标题
content string 文章内容,markdown 格式
tags list 文章标签
id_ string 文章 ID,由随机的4位数字组成
views int 文章被浏览次数
create_at datetime 创建时间
update_at datetime 更新时间

因为此网站用的是 mongo 数据库,类型我就用 python 的类型来标注了;你用其它数据库也是类似的
可以按照你的想法增添字段,比如还可以添加点赞数量等

表设计完之后,手动插入一条数据,为我们展示文章提供测试数据。

2. 文章 HTML 模板

接着设计文章如何展示,即文章展示的 HTML 模板
参照 apps/templates/index.html,新建 apps/templates/article.html 文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{% extends 'base.html' %}

{% block nav %}
  {% include 'nav.html' %}
{% endblock %}

{% block content %}
  <div class="container">
    <h2>{{ title }}</h2>
    <hr class="my-3">
    {{ content }}
  </div>
{% endblock %}

{{ content }} 就是要展示的文章内容

3. 路由与视图

接着设计视图函数将文章数据从数据库中取出来

编辑 server.py 文件,添加文章路由和视图函数:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import markdown

from sanic import Sanic
from sanic import response
from jinja2 import Environment, PackageLoader
from pymongo import MongoClient

app = Sanic('MyAPP')
jinja2 = Environment(loader=PackageLoader('apps', 'templates'))

# mongo 配置
MONGO = {
    'host': '127.0.0.1',
    'port': 27017,
    'username': 'root',
    'password': '123456',
    'authSource': 'admin',
}
client = MongoClient(**MONGO)


def md2html(content_md):
    """markdown 转为 html"""
    content_html = markdown.markdown(
        content_md, extensions=[
            'extra',  # 支持表格等其它
            'codehilite'  # 代码高亮
        ],
    )
    return content_html


@app.get('/')
async def hello_world(request):
    template = jinja2.get_template('index.html')
    context = {
        'msg': 'Hello, world.'
    }
    html = template.render(**context)
    return response.html(html)


@app.get('/<type_>/<id_>/')
async def article_detail(request, type_, id_):
    template = jinja2.get_template('article.html')
    res = client[type_]['article'].find_one({'id_': id_})
    res['content'] = md2html(res['content'])
    del res['_id']
    html = template.render(**res)
    return response.html(html)


if __name__ == '__main__':
    app.run(debug=True, auto_reload=True)

视图函数逻辑也很简单,就是从数据库中取出数据,取出来之后需要将 markdown 格式转为 html 格式;添加了 md2html 函数;还有 mongo 连接的代码

需要安装额外的包:

1
pip install pymongo markdown

访问:比如你的文章类型是 python(对应存储到 mongo 的 python 库中),ID 是 0001,那么访问地址为: http://127.0.0.1:8000/python/0001/


=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1