简体   繁体   English

是否有建议的方法来按程序生成html报告

[英]Is there a recommended way to procedurally build up an html report

I am looking for advice on how I might best turn a large amount of program output into an HTML report. 我正在寻找有关如何最好地将大量程序输出转换为HTML报告的建议。 What I'm basically doing now is building the report up by hand. 我现在基本上要做的是手动建立报告。 The python program I'm working with is very large and has extensive logging throughout. 我正在使用的python程序很大,并且在整个过程中都有大量日志记录。 I'm finding the parts of the logging that I want in my report, marking that up as HTML and appending it to my final result. 我在报告中找到所需的日志记录部分,将其标记为HTML,并将其附加到最终结果中。

I was looking around for an HTML building Python module with the hope that it may be a little more elegant than formatting a bunch of strings by hand. 我一直在寻找一个HTML构建Python模块,希望它比手工格式化一堆字符串更优雅。

This SO question seemed to suggest that HTML building modules are less desirable than newer templating modules: python html generator 这样的问题似乎表明HTML构建模块不如较新的模板模块更可取: python html generator

I'm a little familiar with Jinja and Django templating, but I'm not sure how that would work in my case. 我对Jinja和Django模板有点熟悉,但是我不确定在我的情况下该如何工作。

Thanks for any suggestions. 感谢您的任何建议。

There are multiple ways to generate an HTML from Python. 有多种方法可以从Python生成HTML。

The cleanest option is to use a Template Engine : 最干净的选择是使用模板引擎

  • create a template HTML report with placeholders for variable data 创建带有占位符的模板HTML报告以用于可变数据
  • render the template with a context providing this variable data 使用提供此可变数据的上下文渲染模板

There are multiple standalone (meaning Django is not an option) template engines in Python: Python中有多个独立的(意味着Django不是一个选择)模板引擎:

Example (using mako ): 示例(使用mako ):

  • create an index.tpl template file: 创建一个index.tpl模板文件:

     <html> <head> <title>${title}</title> </head> <body> <h1>${header}</h1> </body> </html> 
  • in the python code, create a Template() instance and render the template: 在python代码中,创建一个Template()实例并呈现该模板:

     >>> from mako.template import Template >>> template = Template(filename='index.tpl') >>> print template.render(title='My Title', header='My Header') <html> <head> <title>My Title</title> </head> <body> <h1>My Header</h1> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM