Login

Prettify HTML body contents in HTTP response

Author:
n1k0
Posted:
November 29, 2010
Language:
Python
Version:
1.2
Tags:
formatting syntax html readability output indentation format tidy templates prettify
Score:
4 (after 4 ratings)

This is an enhancement of snippet #172. Here I use BeautifulSoup — far more easier to install through pip in a virtualenv, and possibly a bit more maintained — to format and properly indent the rendered HTML from templates.

I also added a check to only tidy contents in a DEBUG=True environment, regarding high impact on performance while doing so in production.

Last, it's compatible with Django 1.2.x.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import settings

from BeautifulSoup import BeautifulSoup


class PrettifyMiddleware(object):
    """HTML code prettification middleware."""
    def process_response(self, request, response):
        if settings.DEBUG and response['Content-Type'].split(';', 1)[0] == 'text/html':
            response.content = BeautifulSoup(response.content).prettify()
        return response

More like this

  1. HTML Prettifier by Eloff 7 years, 4 months ago
  2. prettify html by marchino 8 years, 1 month ago
  3. Prettify HTML5 middleware by runejuhl 3 years, 10 months ago
  4. Revisiting Pygments and Markdown by djypsy 7 years, 9 months ago
  5. Sanitize text field HTML (here from the Dojo Toolkit Editor2 widget) by akaihola 8 years, 1 month ago

Comments

cricogik (on December 7, 2010):

It's ok n1k0. Yours version of PrettifyMiddleware is better because #570 don't check DEBUG status.

#

Please login first before commenting.