- https://pypi.org/project/MarkupSafe/
- https://palletsprojects.com/p/markupsafe/
- https://markupsafe.palletsprojects.com/
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('<script>alert(document.cookie);</script>') >>> escape("<strong>Hello</strong>") Markup('<strong>Hello</strong>') >>> # 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>"World"</em>')
Example 2
>>> from markupsafe import escape >>> hello = escape("<em>Hello</em>") >>> hello Markup('<em>Hello</em>') >>> type(hello) <class 'markupsafe.Markup'> >>> print(hello) <em>Hello</em> >>> escape(hello) Markup('<em>Hello</em>') >>> hello + " <strong>World</strong>" Markup('<em>Hello</em> <strong>World</strong>')
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, <em>World</em>!')
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"><script></a>')