Codzy

Web: generating HTML safely

A dynamic website builds HTML pages from data: a list of products becomes <li> items, comments become <p> tags. Frameworks like Flask or Django use templates for this, but the idea fits in an f-string.

Danger: if a visitor writes <script> in a comment and we insert it as is, their code runs for every other visitor. That's the XSS vulnerability. The golden rule: escape any text coming from a user with html.escape, which turns < into &lt;.

from html import escape

products = [("Keyboard", 49.9), ("Mouse <wireless>", 19.5)]

rows = "".join(f"<li>{escape(name)} - {price:.2f} €</li>" for name, price in products)
page = f"<ul>{rows}</ul>"
print(page)

Start the lesson