[mod_python] gzip pages with mod_python

anthony.barker at bmo.com anthony.barker at bmo.com
Tue Mar 23 08:46:28 EST 2004


In php gzipping the pages is fairly trivial. Include this in the file


<?php ob_start("ob_gzhandler"); ?>


Alan Kennedy has a faq for mod_python.
http://www.xhaus.com/alan/python/httpcomp.html#gzip

Grisha - It would be nice to include something closer to the php version 
in the included libraries.


Anthony
--------------------------------------------------------------
import string
import os
import sys
import gzip
import cStringIO
from   mod_python import apache

def compressBuf(buf):
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode = 'wb',  fileobj = zbuf, compresslevel = 6)
    zfile.write(buf)
    zfile.close()
    return zbuf.getvalue()

def testAcceptsGzip(req):
    if req.headers_in.has_key('accept-encoding'):
        encodings = req.headers_in['accept-encoding']
        return (string.find(encodings, "gzip") != -1)
    else:
        return 0

def handler(req):
    req.content_type = "text/html"
    myHtml = """<html><body><h1>hello compressed 
world!</h1></body></html>"""
    if testAcceptsGzip(req):
        zbuf = compressBuf(myHtml)
        req.headers_out['Content-Encoding'] = 'gzip'
        req.headers_out['Content-Length'] = '%d' % (len(zbuf))
        req.send_http_header()
        req.write(zbuf)
    else:
        req.send_http_header()
        req.write(myHtml)
    return apache.OK
#--------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.modpython.org/pipermail/mod_python/attachments/20040323/c50e6398/attachment.html


More information about the Mod_python mailing list