6

我正在创建一个自定义中间件来 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

提前致谢。

4

2 回答 2

8

您可以简单地修改response.content字符串:

response.content = response.content.replace("BAD", "GOOD")
于 2012-06-10T02:38:32.927 回答
0

也许我的回答好一点。当你尝试做 response.content.replace("BAD", "GOOD") 时,你会得到错误,你不能用字符串来做,因为 response.content 是字节数组。我已将语法字符串“gen_duration_time_777”和“server_time_777”添加到基本模板。这对我有用。

import time
from datetime import datetime

class StatsMiddleware(object):
    duration = 0

    def process_request(self, request):
        # Store the start time when the request comes in.
        request.start_time = time.time()

    def process_response(self, request, response):
        # Calculate and output the page generation duration
        # Get the start time from the request and calculate how long
        # the response took.
        self.duration = time.time() - request.start_time

        response["x-server-time"] = datetime.now().strftime("%d/%m/%Y %H:%M")
        response.content = response.content.replace(b"server_time_777", str.encode(response["x-server-time"]))
        response["x-page-generation-duration-ms"] = '{:.3f}'.format(self.duration)
        response.content = response.content.replace(b"gen_duration_time_777", str.encode(response["x-page-generation-duration-ms"]))
        return response
于 2016-02-06T05:16:22.100 回答