我想将外部文本文件中的文本导入到html / jinja日志报告中。
为此,我具有目录结构
│ main.py
│ requirements.txt
│
├───Output
│ log_report.html
│
├───templates
│ template.html
我在其中跑步
from jinja2 import Template, DebugUndefined
from shutil import copyfile
import datetime
import getpass
import os
import socket
def log_start(file_name_template, file_name_log):
copyfile(file_name_template, file_name_log)
template = Template(open(file_name_log).read(), undefined=DebugUndefined)
template_rendered = template.render(date_and_time=datetime.datetime.now().strftime("%Y-%m-%d, %H:%M:%S"),
host_name=socket.gethostname(),
user_name=getpass.getuser(),
requirements="requirements.txt")
return template_rendered
def main(output_dir="Output/",
file_name_basis="log_report"):
file_name_log = output_dir + file_name_basis + ".html"
template_rendered = log_start("templates/template.html", file_name_log)
with open(file_name_log, "w") as file_handle: file_handle.write(template_rendered)
if __name__ == "__main__":
main()
templates/template.html
组成的
<!DOCTYPE html>
<html lang="en">
<body>
<!-- Program execution information. -->
<b>Program execution information.</b><br/>
Date and time: {{date_and_time}}<br/>
Host name: {{host_name}}<br/>
User name: {{user_name}}<br/>
Modules and their versions:<br/>
{{requirements}}
</body>
</html>
代码可以像这样正常运行。但我不想在最终日志报告requirements.txt
中表示log_report.html
,而是希望文件requirements.txt
的内容包含在最终日志报告log_report.html
中。
我已经考虑了
提出的策略https://www.dotnetcurry.com/html5/1167/read-local-file-api-html5-javascript
和
Insert static files literally into Jinja templates without parsing them
但是,对于我来说,这样做如此小巧,它们看起来非常恐怖而且笨拙。
我该如何以一种简短,Python化的方式解决这个问题?
答案 0 :(得分:1)
with open('file_path/filename_with_extension.txt', 'r') as f:
requirements_txt = f.read()
#for pass string var in your example
template_rendered =
template.render(date_and_time=datetime.datetime.now().strftime("%Y-%m-%d, %H:%M:%S"),
host_name=socket.gethostname(), user_name=getpass.getuser(),
requirements=requirements_txt )