Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tornado

Is there a way to avoid prepending "public", "static", etc. to every single javascript src attribute in my HTML files? I'm in the process of converting a basic static server from Node.js to Tornado, and everything has gone smoothly except for this.

The equivalent Node.js/Express code I want to emulate is something like:

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

which effectively changes the serving directory for all content. That way I can do something like <script src="js/foo.js"> rather than <script src="public/js/foo.js">.

All of the solutions I've seen on SO that address static file serving (like this one) leave it at, "just prepend /static".

Here's what I have right now:

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()

When I try and load index.html the HTML renders fine, but I also get this error:

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

like image 283
Connor Gramazio Avatar asked Mar 18 '23 04:03

Connor Gramazio


1 Answers

Just remove /public/ from the route in your handlers table (but leave it in public_root, and move this definition after all the rest (since it will match everything if you let it):

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

You do not need static_path in your settings if you are setting up your own StaticFileHandler.

like image 92
Ben Darnell Avatar answered Apr 25 '23 18:04

Ben Darnell