Python serializes data to HTML

Python Serialize the data to HTML. The last example of serialization will demonstrate the complexity of creating HTML documents. This complexity comes from the fact that we expect to provide a complete web page with a lot of contextual information. One way to solve this HTML problem is as follows:

import string
data_page = string.Template("""
<html>
<head><title>Series <span class="katex math inline">{title}</title></head>
<body>
<h1>Series</span>{title}</h1>
<table>
<thead><tr><td>x</td><td>y</td></tr></thead>
<tbody>
${rows}
</tbody>
</table>
</body>
</html>
""")

@to_bytes
def serialize_html(series: str, data: List[Pair]) -> str:
    """
    >>> data = [Pair(2,3), Pair(5,7)]
    >>> serialize_html("test", data) #doctest: +ELLIPSIS
b'<html>...<tr><td>2</td><td>3</td></tr>n<tr><td>5</td><td>7</td></tr>...
    """
    text = data_page.substitute( title=series,
rows="n".join(
"<tr><td>{0.x}</td><td>{0.y}</td></tr>".format(row)
for row in data)
)
return text

This serialization function consists of two parts. The first is a string.Template() function that contains a basic HTML page. It has two placeholders so that data can be inserted into the document. The ${title} method indicates where the title information can be inserted, while the ${rows} method indicates where the data rows can be inserted.

This function creates each data row using a simple formatting string. These are concatenated into a longer string, which is then substituted into the template.

While this works for the simple example above, it is less ideal for generating more complex datasets. There are many more sophisticated template tools for creating HTML pages, many of which offer features like embedding loops within templates and separating initial serialization functions. For more options, see https://wiki.python.org/moin/Templating.

Leave a Reply

Your email address will not be published. Required fields are marked *