如何使用裝飾器將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:所以?這並不意味着模板不能用於生成轉義文本。 –