Flask HTML Escape Decorator

蓝咒 提交于 2021-02-07 09:51:52

问题


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)


回答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>"



回答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()



回答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;


来源:https://stackoverflow.com/questions/33490888/flask-html-escape-decorator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!