Login

Gzip decorator

Author:
SmileyChris
Posted:
July 24, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Rather than using the full GZipMiddleware, you may want to just compress some views. This decorator lets you do that.

@gzip_compress
def your_view(request, ...):
    ....
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.

from django.middleware.gzip import GZipMiddleware

gzip_middleware = GZipMiddleware()

def gzip_compress(func):
    """
    Gzip compress an individual view rather than requiring the whole site to
    use the Gzip middleware.
    """
    @wraps(func)
    def dec(request, *args, **kwargs):
        response = func(request, *args, **kwargs)
        return gzip_middleware.process_response(request, response)
    return dec

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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

luftyluft (on July 24, 2008):

Note that you can also use django.utils.decorator_from_middleware to achieve the same thing.

from django.utils import decorator_from_middleware
from django.middleware.gzip import GZipMiddleware

@decorator_from_middleware(GZipMiddleware)
def my_view(request):
    pass

#

luftyluft (on July 24, 2008):

sorry, that should have been django.utils.decorators

#

Please login first before commenting.