from subprocess import Popen, PIPE, STDOUT from os import path from genshi.template import MarkupTemplate from pprint import pformat from demo1_basic import serve 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): start_response('404 Not Found', []) return ['File %r not found' % file_path] start_response('200 OK', [('Content-Type', magic(file_path))]) return [open(file_path, 'rb').read()] templates = dict() templates['/'] = MarkupTemplate("""\ """) templates['/environ'] = MarkupTemplate("""\
${pformat(environ)}
""") def pages_app(environ, start_response): try: tmpl = templates[environ['PATH_INFO']] except KeyError: start_response('404 Not Found', []) return ['Not found: %r' % environ['PATH_INFO']] start_response('200 OK', [('Content-Type', 'text/html')]) data = globals(); data.update(locals()) return [tmpl.generate(**data).render()] if __name__ == '__main__': serve(files_app) #serve(pages_app)