新建项目模板
安装库
pip3 install Jinja2 sanic sanic_cors
我使用的库版本:
- Jinja2==3.1.2
- sanic==22.9.1
- sanic_cors==2.2.0
编写扩展插件
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : ext.py
from os.path import abspath, dirname, join
from sanic import HTTPResponse
from sanic.response import html
from jinja2 import Environment, FileSystemLoader
base_dir = abspath(dirname(__file__))
templates_dir = join(base_dir, 'templates')
jinja_env = Environment(loader=FileSystemLoader(templates_dir), autoescape=True)
def render_template(template_name: str, **context) -> HTTPResponse:
template = jinja_env.get_template(template_name)
return html(template.render(**context))
模板页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
名字: {{ name }}<br>
年龄: {{ age }}
</body>
</html>
入口页面
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : main.py
from sanic import Sanic
from sanic.response import json
from sanic_cors import CORS
from ext import render_template
app = Sanic(__name__)
# 设置静态文件目录
app.static("/static", "./static")
@app.route("/")
async def index(request):
return render_template("index.html", name="Jack", age=55)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, workers=4, debug=True)
附件: ext.py
评论区