pythonwebservertornadoembeddedwebserver

Is There a Tornado Equivalent of SimpleHTTPServer?


Looking through the demos, TornadoGists and other gist snippets (based on this previous question), I haven't found any code equivalent to SimpleHTTPServer from the standard library in Python. I'm looking for a really small web server that can handle concurrent requests, with all the boilerplate that SimpleHTTPServer includes for serving up files from the launch directory.


Solution

  • UPDATE: as of Tornado 3, use the built in StaticFileHandler.

    Tornado isn't really designed for serving static files. If this will see any load, you should use nginx, or something like that. And if it won't, it might be easier to use SimpleHTTPServer.

    That said, it's trivial to write one:

    import os.path
    import mimetypes
    
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    
    class FileHandler(tornado.web.RequestHandler):
        def get(self, path):
            if not path:
                path = 'index.html'
    
            if not os.path.exists(path):
                raise tornado.web.HTTPError(404)
    
            mime_type = mimetypes.guess_type(path)
            self.set_header("Content-Type", mime_type[0] or 'text/plain')
    
            outfile = open(path)
            for line in outfile:
                self.write(line)
            self.finish()
    
    def main():
        tornado.options.enable_pretty_logging()
        application = tornado.web.Application([
            (r"/(.*)", FileHandler),
        ])
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    
    if __name__ == "__main__":
        main()
    

    This is just to get you started; if you're going to use it, you should make sure that you can't walk up the filesystem and access any file. Also, the script currently serves itself, which is a bit strange.