2015-11-03 27 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;