Home >Backend Development >Python Tutorial >Generate file reports using Python's Template class

Generate file reports using Python's Template class

WBOY
WBOYforward
2023-04-13 18:13:181609browse

Generate file reports using Python's Template class

Introduction

Many times, I find myself needing to perform tasks that generate reports, output files, or strings. They all more or less follow a pattern, and often the patterns are so similar that we want to have a template that we can reuse and feed data directly into. Fortunately, Python provides a class that can help us: string.Template.

In this article, you will learn how to use this class to generate an output file based on the data you are currently working with, and how to manipulate strings in the same way. So instead of just using examples that you might encounter in your day-to-day work, this article gives you a number of actual tools that you probably know that use this class for generating report files. Let’s get started!

Note: This article is based on Python 3.9.0 (CPython). You can find code examples used throughout this article on GitHub (https://github.com/DahlitzFlorian/generate-file-reports-using-pythons-template-class).

Before looking at an example, let's take some time to look at the advantages of using string.Template over other solutions.

1. No other dependencies are required and it works out of the box, so there is no need to use the pip install command to install it.

2. It is lightweight, and of course template engines such as Jinja2 and Mako have been widely used. However, in the scenario presented in this article, these capabilities are overstated.

3. Separation of concerns: Instead of embedding string manipulation and report generation directly in the code, you can use template files to move them to an external location. If you want to change the structure or design of your report, you can exchange template files without changing your code.

Due to these advantages, some well-known third-party libraries and tools are using it. Wily is an example, and in late 2018, Anthony Shaw, the inventor and maintainer of Wily, wanted to support HTML as the output format for reports generated by wily.

Example: Generating a report of the best books

After discussing the motivation behind using Python’s built-in string.Template class, we’ll look at the A practical example. Imagine that you work for a company that publishes an annual report on the best books published in the past year. 2020 is a special year because in addition to your annual report, you are also releasing a list of the best books of all time.

At this point, we don't care where the data comes from or which books are part of the list. For simplicity, let's assume we have a JSON file called data.json that contains a mapping of author names and book titles as shown below.

{
 "Dale Carnegie": "How To Win Friends And Influence People",
 "Daniel Kahneman": "Thinking, Fast and Slow",
 "Leo Tolstoy": "Anna Karenina",
 "William Shakespeare": "Hamlet",
 "Franz Kafka": "The Trial"
}

Your task now is to share it in a way that can be shared with others (for example, a large magazine, company or blogger). The company decided that a simple table in HTML format would suffice. Now the question is: how to generate this HTML table?

Of course, you can do this manually or create placeholders for each book. But it would be very desirable to have a more general version later, because the list content can be extended or the structural design changed.

Now we can take advantage of Python’s string.Template class! We start by creating the actual template as shown below. Here we call the file template.html.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Great Books of All Time</title>
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
 
 <h1>Great Books of All Time</h1>
 <table >
 <thead>
 <tr>
 <th scope="col">#</th>
 <th scope="col">Author</th>
 <th scope="col">Book Title</th>
 </tr>
 </thead>
 <tbody>
 ${elements}
 </tbody>
 </table>
 
</body>
</html>

The document itself is very rudimentary. We used bootstrap for styling and creating the basic structure of the final table. The header is included, but the data is still missing. Notice that within the tbody element, a placeholder ${elements} is used to mark where we will later inject the list of books.

We put all the Python scripts that are set up to produce the desired output! Therefore, we create a new Python file called report.py in the current working directory. First, we import the two built-in modules required and load the data from a JSON file.

# report.py
import json
import string
with open("data.json") as f:
 data = json.loads(f.read())

Now, the data variable is a dictionary containing the author’s name (key) and book title (value) as key-value pairs. Next, we generate the HTML table and put it into the template (remember placeholders?). So, we initialize an empty string, add new table rows to it as shown below.

content = ""
for i, (author, title) in enumerate(data.items()):
 content += "<tr>"
 content += f"<td>{i + 1}</td>"
 content += f"<td>{author}</td>"
 content += f"<td>{title}</td>"
 content += "</tr>"

This code snippet shows us looping through all the items in the data dictionary and placing the book title as well as the author's name in the corresponding HTML tags. We created the final HTML table. In the next step, we need to load the template file we created earlier:

with open("template.html") as t:
 template = string.Template(t.read())

Note that string.Template accepts a string, not a file path. Therefore, you can also provide a string previously created in the program without saving it to a file. In our case, we provide the contents of the template.html file.

Finally, we use the template's replace() method to replace the placeholder element with the string stored in the variable content. The method returns a string, which we store in the variable final_output. Last but not least, we create a new file called report.html and write the final output to that file.

final_output = template.substitute(elements=content)
with open("report.html", "w") as output:
 output.write(final_output)

现在已经生成了第一个文件报告!如果在浏览器中打开report.html文件,则可以看到结果。

safe_substitution()方法

现在,您已经构建了第一个string.Template用例,在结束本文之前,我想与您分享一个常见情况及其解决方案:安全替换。它是什么?

让我们举个例子:您有一个字符串,您想在其中输入一个人的名字和姓氏。您可以按照以下步骤进行操作:

# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.substitute(firstname="Florian", lastname="Dahlitz")
print(result)

但是,如果您错过传递一个或另一个的值会怎样?它引发一个KeyError。为避免这种情况,我们可以利用safe_substitution()方法。在这种情况下,safe意味着Python在任何情况下都尝试返回有效字符串。因此,如果找不到任何值,则不会替换占位符。

让我们按以下方式调整代码:

# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.safe_substitute(firstname="Florian")
print(result)# Your name is Florian ${lastname}

在某些情况下,这可能是一个更优雅的解决方案,甚至是必须的行为。但是这可能在其他地方引起意外的副作用。

本文概要

在阅读本文时,您不仅学习了Python字符串的基本知识。Template类以及使用它的原因,而且还实现了第一个文件报告脚本!此外,您已经了解了safe_substitution()方法以及在哪种情况下使用它可能会有所帮助。

The above is the detailed content of Generate file reports using Python's Template class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete