简体   繁体   中英

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!

Your code looks correct to me. Put a file named "index.html" in the "app" subdirectory of your current working directory when you run the app, and the contents of that "index.html" will be the response when you visit http://localhost:16001/

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.

Your code should work fine, as @a-jesse-jiryu-davis answered. To expand a bit on it, you could use tornado.web.StaticFileHandler if you just need to serve your static file. This will make it more flexible, and also take advantage of server-side caching etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM