經過上文,我們已經能輸出hello這個單詞。這說明服務已經成功響應。這裡,我們将使用jinja2來進行html的渲染。
jinja2怎麼用,已經超出了本文範圍,是以本文隻講後端的調用。
建立Jinja2服務
回憶一下,在
app.py
中,已經定義了jinja2的服務,代碼如下:
...
@app.listener('before_server_start')
async def setup_db_redis(app, loop):
......
templates_path = os.path.join(os.getcwd(), 'templates')
app.template_env = Environment(
loader=FileSystemLoader(templates_path),
autoescape=select_autoescape(['html', 'xml']),
enable_async=False
)
複制
這裡我使用了
FileSystemLoader
做為loader,避免亂七八糟的問題。
後端渲染
在我寫完這些代碼之時,前端的哥們已經把html檔案寫好了。是以項目中多出了這樣的結構:
├── templates
│ └── web
│ ├── index.html
複制
渲染示例
index.py
檔案:
@games_bp.route('/index', methods=['GET'])
async def index(request):
logging.info("index run")
online_items = await QB_GAMES.where(eq(online=1)).order_by_desc('id').run()
template = request.app.template_env.get_template('web/index.html')
html_content = template.render(online_items=online_items)
return html(html_content)
複制
1.從資料庫中擷取了onlien_items(當然你也可以從其它地方擷取資料)。
2.通過
request.app
擷取到app對象。jinja2的templates做為一個屬性被儲存到了app中。
3.使用jinja函數
get_template
擷取templates對象。
4.使用調用render方法渲染出html
5.用sanic的
html()
方法傳回這個response對象。