date: 2021-11-08title: python之jinja2模板渲染 #标题
tags: #标签
categories: python # 分类
jinja2工具可以将从数据库中查询到的数据,去替换我html中的对应内容(专业名词叫做模板渲染,你先渲染一下,再返回给浏览器),然后再发送给浏览器完成渲染。 这个过程就相当于HTML模板渲染数据。 本质上就是HTML内容中利用一些特殊的符号来替换要展示的数据。
html模板文件
要用到的html模板文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#d1 {
height: 100px;
}
</style>
</head>
<body>
<div id="d1"></div>
<hr/>
<h1>{{ userinfo }}</h1> <!--这是要传入的变量-->
<ul>
<!--下面是将传入的变量进行分别取值,然后渲染到一个列表中-->
{% for k,v in userinfo.items() %}
<li>{{ k }} === {{ v }}</li>
{% endfor %}
</ul>
<hr/>
</body>
</html>
python代码
服务端代码如下:
import pymysql
from wsgiref.simple_server import make_server
from jinja2 import Template
# 从数据库中拿数据
def show_database():
mysql_conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123.com', database='ljz')
cur = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
try:
sql = "select * from userinfo where id = 2"
cur.execute(sql)
return cur.fetchone()
except Exception as exp:
print(exp)
mysql_conn.rollback()
cur.close()
mysql_conn.close()
def html():
# 读html文件内容
with open("t1.html", 'r', encoding='utf-8') as f:
data = f.read()
# 将拿到的内容传给Template方法
tmp = Template(data)
# 从数据库中读数据
userinfo_data = show_database()
# 进行渲染,userinfo是自定义的名字,与html文件中接收变量的名字一致,userinfo_data为数据库中取到的值
data = tmp.render({'userinfo': userinfo_data})
# 返回渲染后的数据
data = data.encode('utf-8')
return data
# 实现http服务的代码
def application(environ, start_response):
# start_response('200 OK', [('k1', 'v1'), ('k2', 'v2')])
start_response('200 OK', [])
path = environ['PATH_INFO']
if path == '/index.html':
ret = html()
else:
ret = b'404 not found!!!!'
return [ret]
httpd = make_server('127.0.0.1', 8080, application)
httpd.serve_forever()
print('Serving HTTP on port 8080...')
运行上述代码后,浏览器访问http://127.0.0.1:8080/index.html
,返回页面如下(正确渲染到数据,则表示jinja2渲染成功):