Search code examples
pythonresttornado

Serving index.html from tornado web server


I'm trying to write a web application and am using Tornado Web for the json xhr calls. But I'm trying to serve a static index.html which is to serve the main app. How can I serve a simple page and still have requesthandlers for the rest of my application?

Here's what I tried so far:

import tornado.ioloop
import tornado.web
import json
import os

games = [...]

class HomeHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

class MatchHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(json.dumps(games))

path = os.path.join(os.getcwd(), 'app')
if __name__ == "__main__":
    application = tornado.web.Application(
        [
            (r'/', HomeHandler),
            (r'/games', MatchHandler),
            (r'/*.*', tornado.web.StaticFileHandler, {'path': path})
        ],
        template_path=os.path.join(os.path.dirname(__file__), 'app')
    )
    application.listen(16001)
    tornado.ioloop.IOLoop.current().start()

Thanks in advance!


Solution

  • The StaticFileHandler regex needs to A) contain a capturing group and B) use regex syntax instead of glob syntax:

    (r'/(.*\..*)', tornado.web.StaticFileHandler, {'path': path})
    

    This will match any paths containing a dot and send it to the StaticFileHandler.