2012-06-10 62 views
4

我正在創建一個自定義中間件來Django編輯響應對象作爲審查。我想找到一種方法來進行一種搜索和替換,用我選擇的一個替換某個詞的所有實例。Django中間件 - 如何編輯Django Response對象的HTML?

我創建了我的中間件對象,將它添加到我的MIDDLEWARE_CLASSES的設置中,並設置它來處理響應。但到目前爲止,我只找到方法來添加/編輯餅乾,設置/刪除字典項目,或寫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 

感謝。

+2

你嘗試過什麼嗎?你非常接近解決方案。 – Tadeck

回答

6

你可以簡單地修改response.content字符串:

response.content = response.content.replace("BAD", "GOOD") 
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