How Markup objects ensure safety
mainMarkupSafe uses a Markup class to track which strings have already been escaped. When you use escape() on a string, it returns a Markup object.
Key behaviors:
- Idempotency: Calling
escape()on an existingMarkupobject does nothing, preventing double-escaping. - Safe Concatenation: When a
Markupobject is concatenated with a standard string, the standard string is automatically escaped before being joined. This prevents injection attacks when building HTML fragments dynamically.
from markupsafe import escape
hello = escape("<em>Hello</em>")
# hello is now a Markup object
# The string " <strong>World</strong>" is automatically escaped because it is being added to a Markup object
combined = hello + " <strong>World</strong>"
# combined is: Markup('<em>Hello</em> <strong>World</strong>')