Working With Safe Text — MarkupSafe documentation
Working With Safe Text
- markupsafe.escape()
Replace the characters
&
,<
,>
,'
, and"
in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML.If the object has an
__html__
method, it is called and the return value is assumed to already be safe for HTML.- Parameters
s – An object to be converted to a string and escaped.
- Returns
A Markup string with the escaped text.
- class markupsafe.Markup(base=, encoding=None, errors='strict')
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.
Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the escape() class method instead.
>>> 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>!')
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.>>> class Foo: ... def __html__(self): ... return '<a href="/foo">foo</a>' ... >>> Markup(Foo()) Markup('<a href="/foo">foo</a>')
This is a subclass of
str
. It has the same methods, but escapes their arguments and returns aMarkup
instance.>>> Markup("<em>%s</em>") % ("foo & bar",) Markup('<em>foo & bar</em>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup('<em>Hello</em> <foo>')
- Parameters
base (Any) –
encoding (Optional[str]) –
errors (str) –
- Return type
- classmethod escape(s)
Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.
- Parameters
s (Any) –
- Return type
- striptags()
unescape() the markup, remove tags, and normalize whitespace to single spaces.
>>> Markup("Main » <em>About</em>").striptags() 'Main » About'
- Return type
str
- unescape()
Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape() 'Main » <em>About</em>'
- Return type
str
Optional Values
- markupsafe.escape_silent()
Like escape() but treats
None
as the empty string. Useful with optional values, as otherwise you get the string'None'
when the value isNone
.>>> escape(None) Markup('None') >>> escape_silent(None) Markup('')
Convert an Object to a String
- markupsafe.soft_str()
Convert an object to a string if it isn’t already. This preserves a Markup string rather than converting it back to a basic string, so it will still be marked as safe and won’t be escaped again.
>>> value = escape("<User 1>") >>> value Markup('<User 1>') >>> escape(str(value)) Markup('&lt;User 1&gt;') >>> escape(soft_str(value)) Markup('<User 1>')