Working With Safe Text¶
-
markupsafe.
escape
(s) → markup¶ Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
-
class
markupsafe.
Markup
¶ 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 the text type (
str
in Python 3,unicode
in Python 2). It has the same methods as that type, but all methods escape their arguments and return aMarkup
instance.>>> Markup('<em>%s</em>') % 'foo & bar' Markup('<em>foo & bar</em>') >>> Markup('<em>Hello</em> ') + '<foo>' Markup('<em>Hello</em> <foo>')
-
classmethod
escape
(s)¶ Escape a string. Calls
escape()
and ensures that for subclasses the correct type is returned.
unescape()
the markup, remove tags, and normalize whitespace to single spaces.>>> Markup('Main » <em>About</em>').striptags() 'Main » About'
-
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>'
-
classmethod