[mod_python] Output Filters Redeaux

Nick nick at dd.revealed.net
Mon Apr 17 12:43:22 EDT 2006


Great example!  Thanks.

On a devel note, it looks like the filter object would be very handy if it
could be treated as in iterator, such as (using the sample code's nomenclature):

for streamlet in filter:
  [do something with streamlet here]

It would definitely turn filter writing into something more Pythonic.  Does
that seem like something that would be useful?

Thanks,
Nick

Lee Brown wrote:
> 
> 
> Greetings!
> 
> Just for fun, here is a handy template for constructing Mod Python
> output filters:
> 
>     from mod_python import apache
>     from cStringIO import StringIO
> 
>     def outputfilter (filter):
>            
>         try:
>             streambuffer = filter.req.streambuffer
>         except AttributeError:
>             filter.req.streambuffer = StringIO() # See Note 1
>             streambuffer = filter.req.streambuffer
>                 # See Note 2
>        
>         streamlet = filter.read()
>         while streamlet:
>                 # See Note 3
>             streambuffer.write(streamlet)
>             streamlet = filter.read()
> 
>         if streamlet is None:
>                 # See Note 4
>             filter.write(streambuffer)
>             filter.close()
> 
> This is as stripped-down, bare-bones as a filter can get, IMHO.  Of
> course, this is just an echo filter until you add your own code to it.
> 
> Note 1:
> 
> When a filter is invoked once or only a few times, there is no real
> advantage in using a cStringIO buffer over a Python List buffer.
> 
> As the number of re-invocations goes up, cStringIO starts to show a
> speed advantage.
> 
> Note 2:
> 
> Anything else that you may want to initialize at the start of a request
> should go here, ex:
>      filter.req.some_variable = some_value
> 
> Note 3:
> 
> Depending on your application, you may want to hack at the raw stream
> before putting it in the buffer, ex:
>     streambuffer.write(streamlet.replace('\r\n', '\n'))
> 
> Note 4:
> 
> At this point, streambuffer contains the entire request response and you
> may go ahead and do whatever it is you wanted to accomplish, ex:
> 
>     filter.write(my_tranform_function(streambuffer))
> 
> 
> 
> Best Regards,
> Lee E. Brown
> (leebrown at leebrown.org)
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python



More information about the Mod_python mailing list