[英]is there a better way to handle index.html with Tornado?
我想知道是否有更好的方法來處理我的Tornado index.html文件。
我對所有請求使用StaticFileHandler,並使用特定的MainHandler來處理我的主要請求。 如果我只使用StaticFileHandler,我得到403:Forbidden錯誤
GET http://localhost:9000/
WARNING:root:403 GET / (127.0.0.1): is not a file
這是我現在的表現:
import os
import tornado.ioloop
import tornado.web
from tornado import web
__author__ = 'gvincent'
root = os.path.dirname(__file__)
port = 9999
class MainHandler(tornado.web.RequestHandler):
def get(self):
try:
with open(os.path.join(root, 'index.html')) as f:
self.write(f.read())
except IOError as e:
self.write("404: Not Found")
application = tornado.web.Application([
(r"/", MainHandler),
(r"/(.*)", web.StaticFileHandler, dict(path=root)),
])
if __name__ == '__main__':
application.listen(port)
tornado.ioloop.IOLoop.instance().start()
事實證明,Tornado的StaticFileHandler已經包含默認文件名功能。
功能在Tornado版本1.2.0中添加: https : //github.com/tornadoweb/tornado/commit/638a151d96d681d3bdd6ba5ce5dcf2bd1447959c
要指定默認文件名,需要將“default_filename”參數設置為WebStaticFileHandler初始化的一部分。
更新你的例子:
import os
import tornado.ioloop
import tornado.web
root = os.path.dirname(__file__)
port = 9999
application = tornado.web.Application([
(r"/(.*)", tornado.web.StaticFileHandler, {"path": root, "default_filename": "index.html"})
])
if __name__ == '__main__':
application.listen(port)
tornado.ioloop.IOLoop.instance().start()
這處理根請求:
/
- > /index.html
子目錄請求:
/tests/
- > /tests/index.html
並且似乎正確處理目錄的重定向,這很好:
/tests
- > /tests/index.html
感謝前面的回答,這是我更喜歡的解決方案:
import Settings
import tornado.web
import tornado.httpserver
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler)
]
settings = {
"template_path": Settings.TEMPLATE_PATH,
"static_path": Settings.STATIC_PATH,
}
tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
def main():
applicaton = Application()
http_server = tornado.httpserver.HTTPServer(applicaton)
http_server.listen(9999)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
和Settings.py
import os
dirname = os.path.dirname(__file__)
STATIC_PATH = os.path.join(dirname, 'static')
TEMPLATE_PATH = os.path.join(dirname, 'templates')
請改用此代碼
class IndexDotHTMLAwareStaticFileHandler(tornado.web.StaticFileHandler):
def parse_url_path(self, url_path):
if not url_path or url_path.endswith('/'):
url_path += 'index.html'
return super(IndexDotHTMLAwareStaticFileHandler, self).parse_url_path(url_path)
現在在你的應用程序中使用該類而不是vanilla StaticFileHandler ...工作完成了!
無需顯式添加StaticFileHandler
; 只需指定static_path,它就會為這些頁面提供服務。
你是否需要MainHandler是正確的,因為出於某種原因,即使你將文件名附加到URL,Tornado也不會提供index.html
文件。
在這種情況下,對代碼的這種輕微修改應該適合您:
import os
import tornado.ioloop
import tornado.web
from tornado import web
__author__ = 'gvincent'
root = os.path.dirname(__file__)
port = 9999
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
application = tornado.web.Application([
(r"/", MainHandler),
], template_path=root,
static_path=root)
if __name__ == '__main__':
application.listen(port)
tornado.ioloop.IOLoop.instance().start()
我一直在嘗試這個。 不要使用渲染,它有額外的解析模板的開銷,並在靜態html中的模板類型字符串上給出錯誤。 我發現這是最簡單的方法。 龍卷風正在尋找正則表達式中的捕獲括號,只需給它一個空的捕獲組。
import os
import tornado.ioloop
import tornado.web
root = os.path.dirname(__file__)
port = 9999
application = tornado.web.Application([
(r"/()", tornado.web.StaticFileHandler, {"path": root, "default_filename": "index.html"})
])
這具有解析/到index.html的效果,還可以避免不需要的解析,例如/views.html到static_dir / views.html
這對我有用起源於龍卷風文檔 :
要在請求目錄時自動提供
index.html
類的文件,請在應用程序設置中設置static_handler_args=dict(default_filename="index.html")
,或者將default_filename
添加為StaticFileHandler
的初始化參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.