Wednesday, May 19, 2010

pylons middleware to strip HTML comments

import re
from webob import Request

class StripHtmlCommentsMiddleware:
    """
    Strips all html comments from response content.
    """
    def __init__(self, app):
        self.app = app
        self.htmlcomments = re.compile(
            '\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>')

    def __call__(self, environ, start_response):
        req = Request(environ)
        rsp = req.get_response(self.app)
        if "text/html" == rsp.content_type:
            new_content = self.htmlcomments.sub('', rsp.unicode_body)
            rsp.unicode_body = new_content
        return rsp(environ, start_response)

No comments:

Post a Comment