Login

Updated version of StripWhitespaceMiddleware (v1.1)

Author:
sleepycal
Posted:
May 31, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Tightens up response content by removed superflous line breaks and whitespace. By Doug Van Horn

---- CHANGES ---- v1.1 - 31st May 2011 Cal Leeming [Simplicity Media Ltd] Modified regex to strip leading/trailing white space from every line, not just those with blank n.

---- TODO ---- * Ensure whitespace isn't stripped from within <pre> or <code> or <textarea> tags.

 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
"""
Tightens up response content by removed superflous line breaks and whitespace.
By Doug Van Horn

---- CHANGES ----
v1.1 - 31st May 2011
Cal Leeming [Simplicity Media Ltd]
Modified regex to strip leading/trailing white space from every line, not just those with blank \n.

---- TODO ----
* Ensure whitespace isn't stripped from within <pre> or <code> or <textarea> tags.

"""

import re

class StripWhitespaceMiddleware:
    """
    Strips leading and trailing whitespace from response content.
    """

    def __init__(self):
        self.whitespace = re.compile('^\s+', re.MULTILINE)
        self.whitespace_trail = re.compile('\s+$', re.MULTILINE)


    def process_response(self, request, response):
        if "text" in response['Content-Type']:
            new_content = self.whitespace.sub('', response.content)
            new_content = self.whitespace_trail.sub('\n', new_content)
            response.content = new_content
            return response
        else:
            return response

More like this

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

Comments

Please login first before commenting.