[mod_python] Transparently using mod_python to handle images

Graham Dumpleton grahamd at dscpl.com.au
Wed Mar 16 21:57:10 EST 2005


Rich McDonough wrote ..
> First let me extend my thanks to this group. It is a fountain of useful
> information.
> 
> I am sure that this question will be easily answered by someone here, in
> fact there is probably some code snippets around that will do the deed
> quickly and easily. I am trying to write a handler that will server 
> images from a subdirectory. The goal is to have the handler serve the 
> image and insert a record into a database indicating the referring page,
> filename, time, etc... It would ideally be a folder within a UserDir, so
> for this to work the user would have to add the appropriate .htaccess 
> and index.py files added to it. Users would then just add the images 
> they want served to the folder, the handler would do the rest.
> 
> I have been doing this with Zope for a while now but need to move away
> from zodb due to size issues. Also, my current approach requires the URL
> to be rather ugly and include an argument (i.e. 
> http://server/folder/image?sparky.jpg). I would love to get away from 
> passing the argument in the URL and simply have users place the real 
> path to the image, then let the handler do the manipulating for me.
> 
> Does anyone have any quick pointers or examples of such an application?

I would not recommend using mod_python.publisher for this, use a
basic content handler instead and you don't have to use form paramaters.
It is actually quite easy, just put the following code in the images
directory as "_images.py".

  from mod_python import apache

  import os

  def handler(req):

    if req.filename == __file__:
      return apache.HTTP_FORBIDDEN
    elif req.filename == __file__ + 'c':
      return apache.HTTP_FORBIDDEN

    if os.path.exists(req.filename):
      apache.log_error("fetch "+req.filename)

    return apache.DECLINED

Modify the log line to what you need as appropriate.

In the .htaccess file for that directory then have:

  SetHandler python-program
  PythonHandler _images

If you then access:

  /images/foo.gif

It will log the access and then by returning apache.DECLINED
pushes the request back to Apache which will then send back
the content of the actual file.

Graham




More information about the Mod_python mailing list