Django Middleware - How to edit a Django Response HTML object?

I create my own django response object editing middleware to act as a censor. I would like to find a way to do a kind of search and replace, replacing all instances of a word with the one that I choose.

I created my middleware object, added it to the MIDDLEWARE_CLASSES settings MIDDLEWARE_CLASSES and configured it to handle the response. But so far I have found methods for adding / editing cookies, setting / deleting dictionary elements, or writing to the end of 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 

Thanks in advance.

+4
python html django
Jun 10 2018-12-12T00:
source share
2 answers

You can simply change the response.content line:

 response.content = response.content.replace("BAD", "GOOD") 
+7
Jun 10 2018-12-12T00:
source share

Perhaps my answer is a little better. When you try to make response.content.replace ("BAD", "GOOD"), you will get an error message that you cannot do this with strings, because response.content is an array of bytes. I added the syntax lines gen_duration_time_777 and server_time_777 to the base template. And it works for me.

 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 
0
Feb 06 '16 at 5:16
source share



All Articles