Code: Alles auswählen
#!/usr/bin/python
# -*- coding: ISO-8859-1 -*-
import os, sys
class ZLIBout:
def __init__( self ):
from zlib import compress
self.compress = compress
def write( self, txt ):
sys.stdout.write( self.compress(txt) )
class Out:
def __init__( self ):
print "Content-Type: text/html"
self.MyStdOut = sys.stdout
self.mode = self.detect_mode()
print 'Content-Encoding: %s\n' % self.mode
self.set_mode()
def write( self, txt ):
self.MyStdOut.write( txt )
def detect_mode( self ):
"Ermittle den möglichen Modus"
if os.environ.has_key('HTTP_ACCEPT_ENCODING'):
modes = os.environ['HTTP_ACCEPT_ENCODING'].split(',')
if "gzip" in modes:
return "gzip"
elif "deflate" in modes:
return "deflate"
return "flat"
def set_mode( self ):
if self.mode == "gzip":
from gzip import GzipFile
sys.stdout = GzipFile(mode='wb', fileobj=sys.stdout)
elif self.mode == "deflate":
MyZLIBout = ZLIBout()
sys.stdout = MyZLIBout
def get_mode( self ):
return self.mode
if __name__ == "__main__":
os.environ['HTTP_ACCEPT_ENCODING'] = "deflate"
MyOut = Out()
print "Das ist ein toller Test Text!"
print MyOut.get_mode
Leider bietet zlib kein fileobj... Zwar gibt es da dieses compressobj() aber das scheind mit was anderes zu sein... Deshalb hab ich dafür auch noch mal eine Klasse geschrieben, die eigentlich das selbe machen sollte wie es gzip.GzipFile() kann...
Aber es gibt ein endlos Loop beim schreiben in ZLIBout.write():
Code: Alles auswählen
Traceback (most recent call last):
File "CompressedOut.py", line 84, in ?
print "Das ist ein toller Test Text!"
File "CompressedOut.py", line 13, in write
print self.compress(txt)
File "CompressedOut.py", line 13, in write
print self.compress(txt)
[...]
Code: Alles auswählen
MyZLIBout = ZLIBout()
MyZLIBout.write("Noch ein Test...")