Search code examples
pythonwebservertornado

Python Tornado render static directory


I am trying to serve a page from a static directory using the Tornado API in Python. This answer is similar to what I am trying to do, but I can't seem to get it to work.

My directory structure looks like this (all of the static files are inside a folder called web):

directory file structure

I have a webserver setup like this:

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/ws', WSHandler),
            (r'/', IndexHandler),
        ]
        settings = {
            "debug": True,
            "static_path": os.path.join(os.path.dirname(__file__), "web")
        }
        tornado.web.Application.__init__(self, handlers, **settings)

http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

I thought this line:

"static_path": os.path.join(os.path.dirname(__file__), "web")

might have fixed the problem, but when I point to the index.html file:

class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render('web/index.html')

It serves the page as expected, but prints this error message to the console:

WARNING:tornado.access:404 GET /css/reset.css (::1) 3.57ms
WARNING:tornado.access:404 GET /js/lib/custom-marker.js (::1) 0.96ms
WARNING:tornado.access:404 GET /js/map.js (::1) 2.08ms
WARNING:tornado.access:404 GET /js/websocket-client.js (::1) 1.56ms
WARNING:tornado.access:404 GET /css/index.css (::1) 0.89ms

In this minimalistic example, how do I fix my problem? Where is it trying to point and not being able to find the files?

Any help you could offer would be greatly appreciated!


Solution

  • According to the documentation section on Static files and aggressive file caching, prefixing your "css" and "js" urls with "web" should solve your problem. For example:

    /css/reset.css should be /web/css/reset.css

    Or just use the recommended static_url in your templates (if you're using them):

    {{ static_url("css/reset.css") }}