【问题标题】:Confused about path settings with Tornado server对 Tornado 服务器的路径设置感到困惑
【发布时间】:2025-12-05 01:00:02
【问题描述】:

我正在使用 bower 为我的网站获取 .css 和 .js 文件。

目录结构如下:

server.py bower_components/ 模板/

所有的 HTML 模板(以及我在 AngularJS 中使用的一些部分模板)都位于模板中。 bower 安装的东西位于 bower_components 中。如何定义 template_path、static_path 和 static_url_prefix 设置,以便我可以链接到这些目录中的文件?

如果我使用像这样的相对路径:

href="bower_components/bootstrap/dist/css/bootstrap.css"

我会收到 404 错误。找不到处理程序,因此引发错误。似乎 Tornado 强迫我在模板上使用 static_url 函数?我真的必须使用它吗?与 AngularJS 混合时看起来很丑。我尝试将 static_path 设置为 os.path.dirname(file) 并尝试使用 static_url 但这给了我例外:

例外:您必须在应用程序中定义“static_path”设置才能使用 static_url

我应该如何配置它?我不敢相信我已经浪费了好几个小时试图弄清楚这一点...... :(

【问题讨论】:

    标签: python-3.x tornado bower


    【解决方案1】:

    您是否尝试使用StaticFileHandler?你可以使用这样的东西:

    import os
    import tornado.web
    import tornado.ioloop
    
    if __name__ == '__main__':
        app = tornado.web.Application([
            (r"/(.*)", tornado.web.StaticFileHandler, {"path": os.path.dirname(os.path.abspath(__file__))}),
        ])
        app.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    

    【讨论】:

      【解决方案2】:

      您必须将静态文件处理程序与您放入设置变量的一些路径变量结合起来。 http://tornado.readthedocs.org/en/latest/web.html 这很容易。您可以根据需要命名任意数量的设置变量。

      【讨论】:

        【解决方案3】:

        原来我需要使用 tornado.web.StaticFileHandler 类,并将路径映射到它。这就是我配置我的 tornado.web.Application 的方式:

        class TornadoApp(tornado.web.Application):
        
            def __init__(self):
                # static file regex patterns matched with the actual folders here
                static_handlers = {
                    '/bower_components/(.*)': 'bower_components',
                    '/templates/partials/(.*)': 'templates/partials'
                }
                handlers = [
                    ('/', IndexHandler),
                    ('/products', ProductHandler),
                ]
                # append the handlers with content from static_handlers dictionary
                for r, p in static_handlers.items():
                    handlers.append((r, tornado.web.StaticFileHandler, {'path': p}))
                settings = {
                    'template_path': "templates",
                    'debug': True
                }
                tornado.web.Application.__init__(self, handlers, **settings)
        

        【讨论】: