简体   繁体   English

从龙卷风Web服务器提供index.html

[英]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. 我试图编写一个Web应用程序,并且正在使用Tornado Web进行json xhr调用。 But I'm trying to serve a static index.html which is to serve the main app. 但是我正在尝试提供一个静态的index.html来服务主应用程序。 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/ 运行该应用程序时,在当前工作目录的“ app”子目录中放置一个名为“ index.html”的文件,当您访问http:// localhost:16001时,该“ index.html”的内容将作为响应/

The StaticFileHandler regex needs to A) contain a capturing group and B) use regex syntax instead of glob syntax: StaticFileHandler正则表达式需要A)包含捕获组,并且B)使用正则表达式语法而不是glob语法:

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

This will match any paths containing a dot and send it to the StaticFileHandler. 这将匹配包含点的所有路径,并将其发送到StaticFileHandler。

Your code should work fine, as @a-jesse-jiryu-davis answered. 您的代码应该可以正常工作,就像@ a-jesse-jiryu-davis回答的那样。 To expand a bit on it, you could use tornado.web.StaticFileHandler if you just need to serve your static file. 为了进一步扩展它,如果只需要提供静态文件,则可以使用tornado.web.StaticFileHandler This will make it more flexible, and also take advantage of server-side caching etc. 这将使其更加灵活,并且还可以利用服务器端缓存等功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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