Cyrin Cyrin - 9 months ago 119
Python Question

Flask HTML Escape Decorator

How would I use a decorator on a route to HTML escape its output. That is, how do I write the

function here:

def index():
return '<html></html>'

(I feel like there should be an extension for this and other simple decorators)

Answer Source

You want to use the cgi module's escape function to do the escaping. Assuming that your function only returns a string, it can be as simple as the following:

import cgi

def html_escape(func):
    def wrapped(*args, **kwargs):
        return cgi.escape(func(*args, **kwargs))
    return wrapped

def index():
    return "<html></html>"

print index()