Cyrin Cyrin - 29 days ago 19
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

html_escape
function here:

@app.route('/')
@html_escape
def index():
return '<html></html>'


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

Answer

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


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

print index()
Comments