学习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)