Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How to do it...

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>', ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content