Many times I find myself needing to perform tasks that generate reports, output files, or strings. They all more or less follow some sort of pattern, and often these patterns are so similar that we want to have a template that we can reuse and input data directly. Fortunately, Python provides a class that can help us:.
In this article, you will learn how to utilize this class to generate an output file based on the data currently in use, and how to manipulate strings in the same way. So, not only does this article use examples that you may encounter in your daily work, it also provides you with a number of actual tools that you may know of and which use this class for generating report files. Let's get started below!
Note: This article is based on Python 3.9.0 (CPython). You can find code samples used throughout this article on GitHub (/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 versus other solutions.
1, no other dependencies, out of the box, so do not need to use pip install command to install.
2, it is lightweight , of course, such as Jinja2 and Mako and other template engines have been widely used . However, in the program presented in this article , these features are overstated .
3, separation of concerns: you can use the template file to move it to an external location, rather than embedding string operations and report generation directly in the code. If you want to change the structure or design of the report, you can exchange the template file without changing the code.
Due to these benefits, a number of well-known third-party libraries and tools are using it. wily is an example of this, and at the end of 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 on best books
After discussing the motivation behind using Python's built-in classes, we'll take a look at the first practical example. Imagine that you are working for a company that publishes an annual report about the best books published in the past year.2020 is a special year because, in addition to your annual report, you will publish a list of the best books ever written.
At this point, we don't care where the data comes from or which books are part of that list. For the sake of simplicity, let's assume we have a named JSON file that contains a mapping of author names to 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" }
You are now tasked with sharing this in a way that can be shared with others (e.g., a large magazine, company, or blogger). The company has decided that a simple form using HTML formatting is sufficient. The question now is: How to generate this HTML table?
Of course, you can perform this operation manually or create placeholders for each book. But it would be very desirable to have a more generalized version later on, as it is possible to expand the list content or change the structural design.
Now we can utilize Python classes! We start by creating the actual template, as shown below. Here, we will call the file.
<!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="/npm/[email protected]/dist/css/" rel="external nofollow" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>Great Books of All Time</h1> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Author</th> <th scope="col">Book Title</th> </tr> </thead> <tbody> ${elements} </tbody> </table> </div> </body> </html>
The document itself is very rudimentary. We used the bootstrap program to style and create the basic structure of the final table. The table header is included, but the data is still missing. Note that in the tbody element, a placeholder $ {elements} is used to mark where we will inject the list of books later.
We have all set up to implement a Python script that generates the desired output! So, we create a new Python file named in the current working directory. First, we import the two required built-in modules and load the data from the JSON file.
# import json import string with open("") as f: data = (())
Now, the data variable is a dictionary containing the author's name (key) and the 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 to which we add a new table row, as follows.
content = "" for i, (author, title) in enumerate(()): content += "<tr>" content += f"<td>{i + 1}</td>" content += f"<td>{author}</td>" content += f"<td>{title}</td>" content += "</tr>"
The code snippet shows us traversing through all the items in the data dictionary and placing the book title as well as the author's name in the appropriate HTML tags. We have created the final HTML table. In the next step, we need to load the template file we created earlier:
with open("") as t: template = (())
Note that a string is accepted instead of a file path. Thus, you can also provide strings previously created in the program without saving them to a file. In our case, we provide the contents of the file.
Finally, we use the template's replace() method to replace the placeholder element with the string stored in the variable's contents. The method returns a string, which we store in the variable final_output. Last but not least, we create a new file named and write the final output to that file.
final_output = (elements=content) with open("", "w") as output: (final_output)
The first file report has now been generated! If you open the file in a browser, you can see the results.
safe_substitution() method
Now that you've built your first use case, I'd like to end this article by sharing with you a common scenario and its solution: safe substitution. What is it?
Let's take an example: you have a string in which you want to enter a person's first and last name. You can follow the steps below:
# safe_substitution.py import string template_string = "Your name is ${firstname} ${lastname}" t = (template_string) result = (firstname="Florian", lastname="Dahlitz") print(result)
But what happens if you miss passing the value of one or the other? It raises a KeyError.To avoid this, we can utilize the safe_substitution() method. In this case, safe means that Python tries to return a valid string in any case. Therefore, if no value can be found, the placeholder will not be replaced.
Let's adjust the code in the following way:
# safe_substitution.py import string template_string = "Your name is ${firstname} ${lastname}" t = (template_string) result = t.safe_substitute(firstname="Florian") print(result) # Your name is Florian ${lastname}
In some cases, this may be a more elegant solution, or even required behavior. But it may cause unintended side effects elsewhere.
Summary of the paper
While reading this article, you have not only learned the basics of Python strings. the Template class and the reasons for using it, but you have also implemented your first file reporting script! In addition, you've learned about the safe_substitution() method and the situations in which it might be helpful to use it.
To this point, this article teaches you to use Python's Template class to generate file reports on the article is introduced to this, more related to Python generate file reports on the contents of the search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!