有没有更好的方法来处理index.html和Tornado?

2024-04-25 05:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文


我想知道是否有更好的方法来处理带有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()

Tags: pathimportselfwebgetindexosport
3条回答

请改用此代码

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)

现在在应用程序中使用该类而不是普通的StaticFileHandler。。。任务完成了!

原来Tornado的StaticFileHandler已经包含了默认文件名功能。

在Tornado 1.2.0版中添加了以下功能: https://github.com/tornadoweb/tornado/commit/638a151d96d681d3bdd6ba5ce5dcf2bd1447959c

要指定默认文件名,需要将“default_file name”参数设置为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')

相关问题 更多 >