Exercise 2: A Legitimate Use of SafeString — Possible Solution ==================================================================== A GENUINE REAL-WORLD CASE ------------------------------ A blog post's body is written in Markdown and converted to HTML by a trusted library before it ever reaches the template: import markdown # a real, trusted third-party conversion step post_html = markdown.markdown("**Bold** and a [link](https://example.com)") # post_html is now a real string containing actual and tags Rendering that value through render_autoescape() UNWRAPPED would escape the very tags the Markdown converter was asked to produce in the first place: render_autoescape("{{ body }}", {"body": post_html}) # -> "<p><strong>Bold</strong> and a # <a href="https://example.com">link</a></p>" That's visibly wrong -- the reader would see literal angle-bracket text instead of bold type and a working link. The fix is to wrap the converter's own output, and only that output, in SafeString before it reaches the template: render_autoescape("{{ body }}", {"body": SafeString(post_html)}) # -> "

Bold and a # link

" # -- real markup, rendered as intended WHY THIS IS DIFFERENT FROM DISABLING ESCAPING GLOBALLY ---------------------------------------------------------- Disabling escaping for the whole template would also fix this one value -- but it would silently remove protection from every OTHER value rendered in that same template at the same time. If the page also displays a comment author's own display name pulled straight from user input, that name is now just as unprotected as the trusted Markdown output, with no way to tell the two apart in the template itself. Wrapping only the Markdown converter's own output in SafeString keeps the default (escape everything) intact for every value that hasn't been explicitly and individually vouched for. The "safe" decision is made exactly once, at the one point in the code that genuinely knows the value came from a trusted conversion step -- not once, globally, at the template level, where there's no way to distinguish a value that's actually safe from one that only looks safe because it's sitting next to something that is. WHY THIS WORKS AS AN ANSWER ---------------------------- It identifies a real, common real-world source of legitimately-safe HTML (a trusted Markdown/HTML conversion step, not an invented example), shows the concrete broken-vs-fixed output the chapter's own render_autoescape() function actually produces for it, and explains the real risk difference between marking one specific value safe and disabling escaping for an entire template.