让 Tornado 使用 javascript 服务静态 HTML 而不使用静态、public 等前缀

Have Tornado serve static HTML with javascript without using static, public, etc. prefix

有没有办法避免在 HTML 文件中的每个 javascript src 属性前添加 "public"、"static" 等?我正在将一个基本的静态服务器从 Node.js 转换为 Tornado,除此之外一切都很顺利。

我要模拟的等效 Node.js/Express 代码类似于:

var app = express();
app.use(express.static(__dirname + '/public'));

这有效地更改了所有内容的服务目录。这样我就可以做 <script src="js/foo.js"> 而不是 <script src="public/js/foo.js">.

我在 SO 上看到的所有解决静态文件服务(如 this one)的解决方案都保留在 "just prepend /static"。

这是我现在拥有的:

import os
import tornado.ioloop
import tornado.web as web

public_root = os.path.join(os.path.dirname(__file__), 'public')

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


handlers = [
  (r'/public/(.*)', web.StaticFileHandler, {'path': public_root}),
  (r'/', MainHandler)
]

settings = dict(
  debug=True,
  static_path=public_root,
  template_path=public_root
)

application = web.Application(handlers, **settings)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

当我尝试加载 index.html 时,HTML 渲染良好,但我也收到此错误:

WARNING:tornado.access:404 GET /bower_components/d3/d3.min.js (::1) 0.55ms

只需从您的处理程序 table 中的路由中删除 /public/(但将其保留在 public_root 中,并将此定义移动 之后 所有其余的(因为如果你愿意,它会匹配所有内容):

handlers = [
  (r'/', MainHandler),
  (r'/(.*)', web.StaticFileHandler, {'path': public_root}),
]

如果您要设置自己的 StaticFileHandler,则您的 settings 中不需要 static_path