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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With