如何使用装饰器将HTML转义出来。也就是说,我怎么写html_escape
功能在这里:Flask HTML Escape装饰器
@app.route('/')
@html_escape
def index():
return '<html></html>'
(我觉得应该有这等简单装饰的延伸)
如何使用装饰器将HTML转义出来。也就是说,我怎么写html_escape
功能在这里:Flask HTML Escape装饰器
@app.route('/')
@html_escape
def index():
return '<html></html>'
(我觉得应该有这等简单装饰的延伸)
瓶都有自己的escape
,DOC:flask.escape
这样,您可以:
from flask import escape
@app.route('/')
def index():
return escape("<html></html>")
如果你坚持使用装饰器:
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>"
flask.escape()和cgi.escape()之间的功能有什么不同? –
flask.escape escape:'&< >''' cgi.escape escapes:'&< >'并且如果标志被设置为'''。 –
您想使用cgi
模块的escape
功能做逃跑。假设你的函数只返回一个字符串,它可以简单,如下:
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()
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>
为什么不使用[templates](http://flask.pocoo.org/docs/0.10/tutorial/templates/)? –
@KevinGuan因为它的API服务器 – Cyrin
@Cyrin:所以?这并不意味着模板不能用于生成转义文本。 –