view static_file_serving.py @ 12:63ea847bfa75

added more stuff
author Atul Varma <avarma@mozilla.com>
date Sat, 12 Jun 2010 22:37:20 -0700
parents
children 7a59f0eceee7
line wrap: on
line source

import mimetypes
import os
import wsgiref.util

class StaticFileApp(object):
    def __init__(self, root_dir):
        self.root_dir = root_dir

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']

        def error_404():
            start_response('404 Not Found',
                           [('Content-Type', 'text/plain')])
            return ['Not Found: %s' % path]

        if path == '/':
            path = '/index.html'

        if path.startswith('/') and environ['REQUEST_METHOD'] == 'GET':
            filename = path.split('/')[1]
            if filename in os.listdir(self.root_dir):
                mimetype, enc = mimetypes.guess_type(filename)
                f = open(os.path.join(self.root_dir, filename))
                start_response('200 OK',
                               [('Content-Type', mimetype)])
                return wsgiref.util.FileWrapper(f)
            else:
                return error_404()

        return error_404()