Middleware for stripping all html comments from the response content before returning it to the client.
This will also strip inline javascript with htmlcomments put around it!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import re
class StripHtmlCommentsMiddleware:
"""
Strips all html comments from response content.
"""
def __init__(self):
self.htmlcomments = re.compile('\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>')
def process_response(self, request, response):
if ("text" in response['Content-Type']):
new_content = self.htmlcomments.sub('', response.content)
response.content = new_content
return response
else:
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Hi, nice code! Something to note: in case you want some comment to pass through (like the conditionals for IE to load extra css), you can make it adding an extra '-' in the comment tag like this:
Cheers, Pedro
#
Please login first before commenting.