XhtmlMortifierMiddleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import re

CONTENT_TYPE_RE = re.compile(r'="application\/xhtml\+xml')
HTML_RE = re.compile(r'html', re.I)

class XhtmlMortifierMiddleware(object):
    """
    This middleware converts responses set with the application/xhtml+xml
    content-type to text/html if the user-agent does not accept XHTML responses.
    Other kind of responses are being ignored.

    Make sure the XhtmlMortifierMiddleware appears after the GZipMiddleware in
    the MIDDLEWARE_CLASSES list in settings.py.
    """

    def _accepts_xhtml(self, request):
        if "/xhtml+xml" in request.META.get("HTTP_ACCEPT", "").lower():
            return True
        else:
            return False

    def process_response(self, request, response):
        if not HTML_RE.search(response["Content-Type"]) or \
                response.has_header('Location'):
            return response
        if self._accepts_xhtml(request) and not \
                response["Content-Type"].split(";")[0] == "text/html":
            response["Content-Type"] = "application/xhtml+xml; charset=utf-8"
        else:
            response["Content-Type"] = "text/html; charset=utf-8"
            response.content = CONTENT_TYPE_RE.sub('="text/html', \
                response.content, 1)
            response['Content-Length'] = str(int(response['Content-Length']) - 12)
        return response

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.