Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 788
Richard Jelte Avatar asked Jun 10 '12 02:06

Richard Jelte


People also ask

Which Middlewares are executed during the response phase?

In Django, middleware is a lightweight plugin that processes during request and response execution. Middleware is used to perform a function in the application. The functions can be a security, session, csrf protection, authentication etc.

What is Authenticationmiddleware in Django?

Authentication middlewareAdds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object. See Authentication in web requests. Middleware for utilizing web server provided authentication. See How to authenticate using REMOTE_USER for usage details.

What is HTTP request in Django?

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

What is HTTP response in Django?

HttpResponse (source code) provides an inbound HTTP request to a Django web application with a text response. This class is most frequently used as a return object from a Django view.


1 Answers

You can simply modify the response.content string:

response.content = response.content.replace("BAD", "GOOD")
like image 86
Ned Batchelder Avatar answered Sep 30 '22 23:09

Ned Batchelder