从 tornado 网络服务器提供服务 index.html
Serving index.html from tornado web server
我正在尝试编写 Web 应用程序并使用 Tornado Web 进行 json xhr 调用。但我正在尝试提供一个静态 index.html 服务,它是为主要应用程序服务的。
我怎样才能提供一个简单的页面并仍然为我的应用程序的其余部分提供请求处理程序?
这是我到目前为止尝试过的:
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()
提前致谢!
我认为你的代码是正确的。当你运行应用程序时,将一个名为"index.html"的文件放在你当前工作目录的"app"子目录中,该"index.html"的内容将是你访问http://localhost:16001/
正如@a-jesse-jiryu-davis 回答的那样,您的代码应该可以正常工作。要对其进行扩展,如果您只需要提供静态文件,则可以使用 tornado.web.StaticFileHandler
。这将使它更加灵活,并且还可以利用 server-side 缓存等
StaticFileHandler 正则表达式需要 A) 包含捕获组和 B) 使用正则表达式语法而不是 glob 语法:
(r'/(.*\..*)', tornado.web.StaticFileHandler, {'path': path})
这将匹配任何包含点的路径并将其发送到 StaticFileHandler。
我正在尝试编写 Web 应用程序并使用 Tornado Web 进行 json xhr 调用。但我正在尝试提供一个静态 index.html 服务,它是为主要应用程序服务的。 我怎样才能提供一个简单的页面并仍然为我的应用程序的其余部分提供请求处理程序?
这是我到目前为止尝试过的:
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()
提前致谢!
我认为你的代码是正确的。当你运行应用程序时,将一个名为"index.html"的文件放在你当前工作目录的"app"子目录中,该"index.html"的内容将是你访问http://localhost:16001/
正如@a-jesse-jiryu-davis 回答的那样,您的代码应该可以正常工作。要对其进行扩展,如果您只需要提供静态文件,则可以使用 tornado.web.StaticFileHandler
。这将使它更加灵活,并且还可以利用 server-side 缓存等
StaticFileHandler 正则表达式需要 A) 包含捕获组和 B) 使用正则表达式语法而不是 glob 语法:
(r'/(.*\..*)', tornado.web.StaticFileHandler, {'path': path})
这将匹配任何包含点的路径并将其发送到 StaticFileHandler。