MarkupSafe

MarkupSafe implements a text object that escapes characters so it is safe to use in HTML and XML. Characters that have special meanings are replaced so that they display as the actual characters. This mitigates injection attacks, meaning untrusted user input can safely be displayed on a page. Escaping is implemented in C so it is as efficient as possible.

Installing

pip install -U MarkupSafe

Example 1

>>> from markupsafe import Markup, escape

>>> # escape replaces special characters and wraps in Markup
>>> escape("<script>alert(document.cookie);</script>")
Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')

>>> escape("<strong>Hello</strong>")         
Markup('&lt;strong&gt;Hello&lt;/strong&gt;')

>>> # wrap in Markup to mark text "safe" and prevent escaping
>>> Markup("<strong>Hello</strong>")
Markup('<strong>hello</strong>')

>>> escape(Markup("<strong>Hello</strong>"))
Markup('<strong>hello</strong>')

>>> # Markup is a str subclass
>>> # methods and operators escape their arguments
>>> template = Markup("Hello <em>{name}</em>")
>>> template.format(name='"World"')
Markup('Hello <em>&#34;World&#34;</em>')

Example 2

>>> from markupsafe import escape
>>> hello = escape("<em>Hello</em>")
>>> hello
Markup('&lt;em&gt;Hello&lt;/em&gt;')
>>> type(hello)
<class 'markupsafe.Markup'>
>>> print(hello)
&lt;em&gt;Hello&lt;/em&gt;

>>> escape(hello)
Markup('&lt;em&gt;Hello&lt;/em&gt;')
>>> hello + " <strong>World</strong>"
Markup('&lt;em&gt;Hello&lt;/em&gt; &lt;strong&gt;World&lt;/strong&gt;')

Example 3

A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe.

>>> from markupsafe import Markup

>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')

>>> Markup(42)
Markup('42')

>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello, &lt;em&gt;World&lt;/em&gt;!')

Example 4

This implements the __html__() interface that some frameworks use. Passing an object that implements __html__() will wrap the output of that method, marking it safe.

>>> from markupsafe import Markup

>>> class Foo:
...     def __html__(self):
...         return '<a href="/foo">foo</a>'
...

>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')

Example 5 – HTML Representations

from markupsafe import Markup

class Image:
    def __init__(self, url):
        self.url = url

    def __html__(self):
        return f'<img src="{self.url}">'

>>> img = Image("/static/logo.png")
>>> Markup(img)
Markup('<img src="/static/logo.png">')
from markupsafe import Markup, escape

class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __html__(self):
        return f'<a href="/user/{self.id}">{escape(self.name)}</a>'

>>> user = User(3, "<script>")
>>> escape(user)
Markup('<a href="/users/3">&lt;script&gt;</a>')