Skip to main content
 首页 » 编程设计

python之Flask HTML 转义装饰器

2025年05月04日10yxwkf

如何在 HTML 转义其输出的路径上使用装饰器。也就是说,我如何在此处编写 html_escape 函数:

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

(我觉得应该有这个和其他简单装饰器的扩展)

请您参考如下方法:

Flask 有自己的escape,文档: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>"