~ubuntu-branches/ubuntu/edgy/libapache2-mod-python/edgy

« back to all changes in this revision

Viewing changes to examples/gzipfilter.py

  • Committer: Bazaar Package Importer
  • Author(s): Thom May
  • Date: 2004-09-06 20:27:57 UTC
  • Revision ID: james.westby@ubuntu.com-20040906202757-yzpyu1bcabgpjtiu
Tags: upstream-3.1.3
ImportĀ upstreamĀ versionĀ 3.1.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# $Id: gzipfilter.py,v 1.1 2002/10/04 21:31:05 grisha Exp $
 
2
#
 
3
# Usage:
 
4
#   <Directory /where/ever>
 
5
#     PythonOutputFilter gzipfilter
 
6
#     SetOutputFilter gzipfilter
 
7
#   </Directory>
 
8
 
 
9
from mod_python import apache
 
10
 
 
11
import os
 
12
import sys
 
13
import gzip
 
14
import cStringIO
 
15
from   mod_python import apache
 
16
 
 
17
def compress(s):
 
18
    sio = cStringIO.StringIO()
 
19
    f = gzip.GzipFile(mode='wb',  fileobj=sio)
 
20
    f.write(s)
 
21
    f.close()
 
22
    return sio.getvalue()
 
23
 
 
24
def accepts_gzip(req):
 
25
    if req.headers_in.has_key('accept-encoding'):
 
26
        encodings = req.headers_in['accept-encoding']
 
27
        return (encodings.find("gzip") != -1)
 
28
    return 0
 
29
 
 
30
###
 
31
### main filter function
 
32
###
 
33
def outputfilter(filter):
 
34
 
 
35
    if (filter.req.main or
 
36
        not accepts_gzip(filter.req)):
 
37
        
 
38
        # Presense of filter.req.main tells us that
 
39
        # we are in a subrequest. We don't want to compress
 
40
        # the data more than once, so we pass_on() in
 
41
        # subrequests. We also pass_on() if the client
 
42
        # does not accept gzip encoding, of course.
 
43
 
 
44
        filter.pass_on()
 
45
    else:
 
46
        
 
47
        if not filter.req.sent_bodyct:
 
48
 
 
49
            # the above test allows us to set the encoding once
 
50
            # rather than every time the filter is invoked
 
51
            
 
52
            filter.req.headers_out['content-encoding'] = 'gzip'
 
53
 
 
54
        # loop through content, compressing
 
55
 
 
56
        s = filter.read()
 
57
 
 
58
        while s:
 
59
            s = compress(s)
 
60
            filter.write(s)
 
61
            s = filter.read()
 
62
 
 
63
        if s is None:
 
64
 
 
65
            # this means we received an EOS, so we pass it on
 
66
            # by closing the filter
 
67
            
 
68
            filter.close()
 
69
 
 
70
 
 
71
 
 
72