Commits

Anonymous committed a2560e4

Added a basic XHTMLifyMiddleware.

Comments (0)

Files changed (2)

strainer/middleware.py

 """Provides WSGI middleware for validating and tidying HTML output."""
+import re
+import xhtmlify
 import logging
 try:
     from cStringIO import StringIO
     from StringIO import StringIO
 
 
-__all__ = ['XHTMLValidatorMiddleware']
+__all__ = ['XHTMLValidatorMiddleware', 'XHTMLifyMiddleware']
 
 
 LOG = logging.getLogger('strainer.middleware')
 except ImportError:
     pass  # no lxml, no XHTMLValidatorMiddleware, sorry.
 
+
+class XHTMLifyMiddleware(BufferingMiddleware):
+    def filter(self, status, headers, exc_info, response):
+        content_type = get_content_type(headers)
+        parts = content_type.split(';', 1)
+        if len(parts)==2:
+            content_type, rest = parts
+        else:
+            rest = ''
+        encoding = re.search(
+            r"""charset\s*=\s*("[A-Za-z0-9_-]*"|"""
+                           r"""'[A-Za-z0-9_-]*'|"""
+                           r"""[A-Za-z0-9_-]*)""", rest)
+        if encoding:
+            encoding = encoding.group(1).replace('"', '').replace("'", '')
+        if content_type.strip() in ('text/html', 'application/xml+html'):
+            response = xhtmlify.xhtmlify(response, encoding=encoding)
+        return response

tests/test_middleware.py

 import logging
+from strainer.middleware import XHTMLifyMiddleware
 try:
     from strainer.middleware import XHTMLValidatorMiddleware
 except ImportError:
     assert response==['<html>'], repr(response)
     assert errors==['Validation failed: no DTD found !, line 1, column 6']
 
+def test_xhtmlify_middleware_runs():
+    """This test is expected to fail if lxml isn't available."""
+    app = XHTMLifyMiddleware(FakeWSGIApp('<html>'))
+    response = app({}, fake_start_response)
+    assert response==['<html xmlns="http://www.w3.org/1999/xhtml"></html>']