【问题标题】:Django Middleware - How to edit the HTML of a Django Response object?Django 中间件 - 如何编辑 Django 响应对象的 HTML?
【发布时间】:2012-06-13 12:37:18
【问题描述】:

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

提前致谢。

【问题讨论】:

  • 你有没有尝试过?您非常接近解决方案。

标签: python html django


【解决方案1】:

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

response.content = response.content.replace("BAD", "GOOD")

【讨论】:

    【解决方案2】:

    也许我的回答好一点。当您尝试制作 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2011-04-10
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多