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)

Enquirer: lynn

||

Solution #1:

Flask has its own escape, doc: flask.escape

so, you can:

from flask import escape

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

if you insist on using decorator:

from functools import wraps
from flask import escape

def my_escape(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        return escape(func(*args, **kwargs))
    return wrapped

@app.route('/')
@my_escape
def index():
    return "<html></html>"
Respondent: lynn

Solution #2:

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()
Respondent: lord63. j

Solution #3:

html_escape_table = {
    "&": "&amp;",
    '"': "&quot;",
    "'": "&apos;",
    ">": "&gt;",
    "<": "&lt;",
}
def html_escape(text):
    return "".join(html_escape_table.get(c,c) for c in text)

print html_escape("<a>test</a>")

result -> &lt;a&gt;test&lt;/a&gt;
Respondent: skyler

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.