Send a random (avatar) image

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Random Avatar
~~~~~~~~~~~~~

You might want to use this as your avatar picture in discussion
forums.

With a chance of 1:ratio, one of the images in the current
directory will be randomly selected and sent to the browser.
Otherwise, the given default image will be used.

To get a random selection from all images, set
``DEFAULT_IMAGE = ''``.

Python 2.5 or higher is required.

If the script's ``.py`` ending is not accepted by forums, you can
use `mod_rewrite`_ to create an alias. In the same directory as
the script, create a .htaccess file with this content (without
leading whitespace)::

    RewriteEngine On
    Options +FollowSymLinks

    RewriteRule ^avatar.jpg$    avatar.py   [PT,L]

:Copyright: 2005-2008 Jochen Kupperschmidt
:Date: 13-Nov-2008
:License: MIT

.. _mod_rewrite: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
"""

from __future__ import with_statement
from itertools import ifilterfalse
import os
from random import choice
import sys
import time


# Adjust these values.
DEFAULT_IMAGE = 'your_default_image.png'
RATIO = 5

# MIME types according to file extension.
MIMETYPES = {
    'gif': 'image/gif',
    'jpg': 'image/jpeg',
    'png': 'image/png',
    }

def get_ext(filename):
    """Return the filename's extension."""
    return filename.rpartition('.')[-1]

def choose_image():
    """Choose the name of an image to display."""
    # Build a list of files in the current directory.
    images = ifilterfalse(os.path.isdir, os.listdir(os.curdir))

    # Only keep the file extensions defined above.
    images = filter(lambda image: get_ext(image) in MIMETYPES, images)

    # Return a random image if no default image is set.
    if not DEFAULT_IMAGE:
        return choice(images)

    # Return default image depending on the timestamp.
    if int(time.time()) % RATIO != 0:
        return DEFAULT_IMAGE

    # Remove default image from list.
    if DEFAULT_IMAGE in images:
        images.remove(DEFAULT_IMAGE)

    # Select random image.
    return choice(images)

if __name__ == '__main__':
    image = choose_image()
    type_ = MIMETYPES[get_ext(image)]
    sys.stdout.write('Content-Type: %s\n\n' % type_)
    with open(image, 'rb')as f:
        sys.stdout.write(f.read())