[英]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()
提前致謝!
您的代碼對我來說看起來正確。 運行該應用程序時,在當前工作目錄的“ app”子目錄中放置一個名為“ index.html”的文件,當您訪問http:// localhost:16001時,該“ index.html”的內容將作為響應/
StaticFileHandler正則表達式需要A)包含捕獲組,並且B)使用正則表達式語法而不是glob語法:
(r'/(.*\..*)', tornado.web.StaticFileHandler, {'path': path})
這將匹配包含點的所有路徑,並將其發送到StaticFileHandler。
您的代碼應該可以正常工作,就像@ a-jesse-jiryu-davis回答的那樣。 為了進一步擴展它,如果只需要提供靜態文件,則可以使用tornado.web.StaticFileHandler
。 這將使其更加靈活,並且還可以利用服務器端緩存等功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.