Django Middleware - 如何编辑Django Response对象的HTML?

Ric*_*lte 5 html python django

我正在创建一个自定义中间件来django编辑响应对象以充当审查员.我想找到一种方法来进行一种搜索和替换,用我选择的一个单词取代某些单词的所有实例.

我已经创建了我的中间件对象,将其添加到我MIDDLEWARE_CLASSES的设置中并将其设置为处理响应.但到目前为止,我只找到了添加/编辑cookie,设置/删除字典项或写入html末尾的方法:

class CensorWare(object):
    def process_response(self, request, response):
        """
        Directly edit response object here, searching for and replacing terms
        in the html.
        """
        return response
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ned*_*der 7

您只需修改response.content字符串即可:

response.content = response.content.replace("BAD", "GOOD")
Run Code Online (Sandbox Code Playgroud)