r"""Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the `__html__` interface a couple of frameworks and web applications use. :class:`Markup` is a direct subclass of `unicode` and provides all the methods of `unicode` just th
| 21 | |
| 22 | |
| 23 | class Markup(text_type): |
| 24 | r"""Marks a string as being safe for inclusion in HTML/XML output without |
| 25 | needing to be escaped. This implements the `__html__` interface a couple |
| 26 | of frameworks and web applications use. :class:`Markup` is a direct |
| 27 | subclass of `unicode` and provides all the methods of `unicode` just that |
| 28 | it escapes arguments passed and always returns `Markup`. |
| 29 | |
| 30 | The `escape` function returns markup objects so that double escaping can't |
| 31 | happen. |
| 32 | |
| 33 | The constructor of the :class:`Markup` class can be used for three |
| 34 | different things: When passed an unicode object it's assumed to be safe, |
| 35 | when passed an object with an HTML representation (has an `__html__` |
| 36 | method) that representation is used, otherwise the object passed is |
| 37 | converted into a unicode string and then assumed to be safe: |
| 38 | |
| 39 | >>> Markup("Hello <em>World</em>!") |
| 40 | Markup(u'Hello <em>World</em>!') |
| 41 | >>> class Foo(object): |
| 42 | ... def __html__(self): |
| 43 | ... return '<a href="#">foo</a>' |
| 44 | ... |
| 45 | >>> Markup(Foo()) |
| 46 | Markup(u'<a href="#">foo</a>') |
| 47 | |
| 48 | If you want object passed being always treated as unsafe you can use the |
| 49 | :meth:`escape` classmethod to create a :class:`Markup` object: |
| 50 | |
| 51 | >>> Markup.escape("Hello <em>World</em>!") |
| 52 | Markup(u'Hello <em>World</em>!') |
| 53 | |
| 54 | Operations on a markup string are markup aware which means that all |
| 55 | arguments are passed through the :func:`escape` function: |
| 56 | |
| 57 | >>> em = Markup("<em>%s</em>") |
| 58 | >>> em % "foo & bar" |
| 59 | Markup(u'<em>foo & bar</em>') |
| 60 | >>> strong = Markup("<strong>%(text)s</strong>") |
| 61 | >>> strong % {'text': '<blink>hacker here</blink>'} |
| 62 | Markup(u'<strong><blink>hacker here</blink></strong>') |
| 63 | >>> Markup("<em>Hello</em> ") + "<foo>" |
| 64 | Markup(u'<em>Hello</em> <foo>') |
| 65 | """ |
| 66 | __slots__ = () |
| 67 | |
| 68 | def __new__(cls, base=u'', encoding=None, errors='strict'): |
| 69 | if hasattr(base, '__html__'): |
| 70 | base = base.__html__() |
| 71 | if encoding is None: |
| 72 | return text_type.__new__(cls, base) |
| 73 | return text_type.__new__(cls, base, encoding, errors) |
| 74 | |
| 75 | def __html__(self): |
| 76 | return self |
| 77 | |
| 78 | def __add__(self, other): |
| 79 | if isinstance(other, string_types) or hasattr(other, '__html__'): |
| 80 | return self.__class__(super(Markup, self).__add__(self.escape(other))) |
no outgoing calls
no test coverage detected
searching dependent graphs…