这篇文章主要介绍了python 利用jinja2模板生成html代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from
jinja2
import
Environment, FileSystemLoader
import
json
def
generate_html(data):
env
=
Environment(loader
=
FileSystemLoader(
'./'
))
# 加载模板
template
=
env.get_template(
'模板.html'
)
# template.stream(body).dump('result.html', 'utf-8')
with
open
(
"result.html"
,
'w'
) as fout:
html_content
=
template.render(data
=
{})
fout.write(html_content)
# 写入模板 生成html
if
__name__
=
=
"__main__"
:
result
=
{}
generate_html(result)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#### 脚本执行 添加进度信息ff = open('1.txt','w')
def
open_file(file_name):
try
:
with
open
(file_name,
'a+'
)as f:
# 例如打开一个大文件
fsize
=
os.path.getsize(file_name)
# 先计算大文件大小
line_list_size
=
0
for
line_list
in
f:
line_list_size
+
=
sys.getsizeof(line_list)
# 计算处理文件大小
done
=
int
(
float
(line_list_size)
/
fsize
*
10
)
# 计算进度
sys.stdout.write(
"\r[%s%s] %d%%"
%
(
'█'
*
done
*
2
,
' '
*
(
20
-
done
*
2
),
10
*
done))
sys.stdout.flush()
# 刷新到控制台
except
Exception, e:
print
e
return
'文件操作失败'
if
__name__
=
=
"__main__"
:
file_name
=
'235'
print
'---- start ----'
open_file(file_name)
print
'\n---- end ----'
TEMPLATE_ENVIRONMENT = Environment(loader=FileSystemLoader(os.path.join(PATH, 'templates')), autoescape=False, trim_blocks=False) def render_template(template_filename, context): return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
with open(target, 'w') as f:
html = render_template(tpl, context)
f.write(html)
|
来源:oschina
链接:https://my.oschina.net/u/3005325/blog/4486078