Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 173.9MB ·虚拟内存 1439.3MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
模板引擎是一个旨在将模板与数据模型结合以生成结果文档的库。
默认情况下,Bottle 使用自带的简单的模板引擎。
$ mkdir botview && cd botview $ mkdir views $ touch views/show_cars.tpl app.py
我们为应用创建目录和文件。
views/show_cars.tpl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cars</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
% for car in cars:
<tr>
<td>{{car['name']}}</td>
<td>{{car['price']}}</td>
</tr>
% end
</table>
</body>
</html>
在此模板中,我们浏览接收到的cars对象并从中生成一个表。 模板文件位于views目录中。
app.py
#!/usr/bin/env python3
from bottle import route, run, template, HTTPResponse
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
@route('/cars')
def getcars():
db = client.testdb
data = db.cars.find({}, {'_id': 0})
if data:
return template('show_cars', cars=data)
else:
return HTTPResponse(status=204)
run(host='localhost', port=8080, debug=True)
在应用中,我们从 MongoDB 集合中检索数据。 我们使用template()功能将模板文件与数据结合在一起。