from subprocess import Popen, PIPE, STDOUT from os import path from genshi.template import MarkupTemplate from pprint import pformat from demo1_basic import serve from demo3_getparams import err_404, slides_app def redirect(environ, start_response, dest='/'): start_response('302 Found', [('Location', dest)]) return [] def magic(path): p = Popen(['file', '-bi', path], stdout=PIPE, stderr=STDOUT) return p.communicate()[0].strip() def files_app(environ, start_response): file_path = environ['PATH_INFO'][1:] if not path.isfile(file_path): return err_404(environ, start_response) start_response('200 OK', [('Content-Type', magic(file_path))]) return [open(file_path, 'rb').read()] templates = dict() templates['/'] = MarkupTemplate("""\ """) templates['/environ'] = MarkupTemplate("""\

The WSGI environment

${pformat(environ)} """) def pages_app(environ, start_response): try: tmpl = templates[environ['PATH_INFO']] except KeyError: return err_404(environ, start_response) start_response('200 OK', [('Content-Type', 'text/html')]) data = globals(); data.update(locals()) return [tmpl.generate(**data).render()] def environ_app(environ, start_response): from pprint import pformat start_response('200 OK', [('Content-Type', 'text/plain')]) return [pformat(environ)] def dispatcher(url_map): def dispatch(environ, start_response): path_info = environ['PATH_INFO'] for prefix, app in url_map: if path_info.startswith(prefix): lp = len(prefix) environ['SCRIPT_NAME'] += path_info[:lp] environ['PATH_INFO'] = path_info[lp:] return app(environ, start_response) return err_404(environ, start_response) return dispatch if __name__ == '__main__': my_url_map = [ ('/file', files_app), ('/slide', slides_app), ('/environ', environ_app), ('/page', pages_app), ] serve(dispatcher(my_url_map))