Login

XhtmlMortifierMiddleware

Author:
jgelens
Posted:
April 9, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

This middleware checks for xhtml mimetypes if the browser supports a "application/xhtml+xml" response. If not, it converts the response headers to "text/html".

To enable this middleware add it the the MIDDLEWARE_CLASSES setting and make sure it appears somewhere after GZipMiddleware, so that it's processed first.

 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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.