6

I'm creating a custom middleware to django edit response object to act as a censor. I would like to find a way to do a kind of search and replace, replacing all instances of some word with one that I choose.

I've created my middleware object, added it to my MIDDLEWARE_CLASSES in settings and have it set up to process the response. But so far, I've only found methods to add/edit cookies, set/delete dictionary items, or write to the end of the 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.

1
  • 2
    Have you tried anything? You are very close to the solution.
    – Tadeck
    Jun 10, 2012 at 2:48

2 Answers 2

9

You can simply modify the response.content string:

response.content = response.content.replace("BAD", "GOOD")
1
  • 1
    I get an error a bytes-like object is required, not 'str' from Django 3.2.9 with that approach. It should be response.content.replace(b"_WEBFLOW_MAGIC", b"") (motice the bs). Jan 29, 2022 at 22:45
1

Perhaps my reply little better. When you try to make response.content.replace("BAD", "GOOD"), you will get error, that you cannot do it with strings, because response.content is byte array. I've added syntactic strings 'gen_duration_time_777' and 'server_time_777' to base template. And this 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.