问题
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 = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
return "".join(html_escape_table.get(c,c) for c in text)
print html_escape("<a>test</a>")
result -> <a>test</a>
来源:https://stackoverflow.com/questions/33490888/flask-html-escape-decorator