Sanic templates html详解

学习sanic, 直接百度【sanic】看文档, 如:https://www.osgeo.cn/sanic/

讲解的比较清楚,养成看文档的习惯。

本文的重点在下面:
在sanic中不能直接使用html,需要引入jinja2

使用如下(也适用蓝图)
代码适用于win 和Linux(我之前写了其他code,在win可以,在ubuntu上出错了)

from jinja2 import Environment, select_autoescape, FileSystemLoader
from sanic import html

class JinJaTemplate(object):
    def __init__(self):
        self.template_paths = ["./templates"]
        self.env_sync = Environment(loader=FileSystemLoader(self.template_paths),
                                    autoescape=select_autoescape(['html', 'xml', 'tpl']),
                                    enable_async=False)
        self.enable_async_flag = sys.version_info >= (3, 6)
        self.env_async = Environment(loader=FileSystemLoader(self.template_paths),
                                     autoescape=select_autoescape(['html', 'xml', 'tpl']),
                                     enable_async=self.enable_async_flag)

    def template_render_sync(self, template_file, **kwargs):
        template = self.env_sync.get_template(template_file)
        rendered_template = template.render(kwargs)
        return html(rendered_template)

    async def template_render_async(self, template_file, **kwargs):
        template = self.env_async.get_template(template_file)
        rendered_template = await template.render_async(kwargs)
        return html(rendered_template)

初始化:
将这个放到一个公有文件中, 如 sanic_common.py

JinJaTemplate = JinJaTemplate()

template = JinJaTemplate.template_render_sync
template_async = JinJaTemplate.template_render_async

在蓝图或其他地方使用,
就可以使用templates目录下的:ETL/tool.html

from sanic_common import *
SERVER_INDEX = Blueprint("server_index", url_prefix='/index')
@SERVER_INDEX.route("/", methods=["GET"])
async def post_index(request):
    data = {"a":1, "b":2}
    return template('ETL/tool.html', **data)

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值