我想知道是否有更好的方法来处理带有Tornado的index.html文件。
我对所有请求使用StaticFileHandler,并使用特定的MainHandler处理我的主请求。如果我只使用StaticFileHandler,我得到一个403:禁止的错误
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()
请改用此代码
现在在应用程序中使用该类而不是普通的StaticFileHandler。。。任务完成了!
原来Tornado的StaticFileHandler已经包含了默认文件名功能。
在Tornado 1.2.0版中添加了以下功能: https://github.com/tornadoweb/tornado/commit/638a151d96d681d3bdd6ba5ce5dcf2bd1447959c
要指定默认文件名,需要将“default_file name”参数设置为WebStaticFileHandler初始化的一部分。
更新示例:
它处理根请求:
/
->;/index.html
子目录请求:
/tests/
->;/tests/index.html
并正确处理目录的重定向,这很好:
/tests
->;/tests/index.html
感谢前面的回答,下面是我更喜欢的解决方案:
和Settings.py
相关问题 更多 >
编程相关推荐