August 2018
Intermediate to advanced
366 pages
10h 14m
English
Combining the string.Formatter and cgi modules, it is possible to create a formatter that takes care of escaping for us:
import string
import cgi
class HTMLFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
val, key = super().get_field(field_name, args, kwargs)
if hasattr(val, '__html__'):
val = val.__html__()
elif isinstance(val, str):
val = cgi.escape(val)
return val, key
class Markup:
def __init__(self, v):
self.v = v
def __str__(self):
return self.v
def __html__(self):
return str(self)
Then we can use the HTMLFormatter and the Markup classes while also retaining the ability to inject raw html when needed:
>>> html = HTMLFormatter().format('Hello {name}, you are {title}', name='<strong>Name</strong>', ...