2015-11-03 88 views
0

如何使用装饰器将HTML转义出来。也就是说,我怎么写html_escape功能在这里:Flask HTML Escape装饰器

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

(我觉得应该有这等简单装饰的延伸)

+1

为什么不使用[templates](http://flask.pocoo.org/docs/0.10/tutorial/templates/)? –

+0

@KevinGuan因为它的API服务器 – Cyrin

+1

@Cyrin:所以?这并不意味着模板不能用于生成转义文本。 –

回答

6

瓶都有自己的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>" 
+0

flask.escape()和cgi.escape()之间的功能有什么不同? –

+1

flask.escape escape:'&< >''' cgi.escape escapes:'&< >'并且如果标志被设置为'''。 –

1

您想使用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() 
0
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;