Search code examples
pythonservertornado

How to set path for tornado server


I'm building a server with python tornado. My colleague has finished the frontend part.

I've done a very simple test as below:

class IndexHandler(tornado.web.RequestHandler):
        def get(self):
            print("this is a get request from indexhandler:\n")
            print(self.request)
            self.render("frontend/index.html")

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

For this test, the browser get 500: Internal Server Error. Because the index.html contains some js files in sub directories.
Here is the messages of the server:

[I 170430 23:06:21 web:2063] 200 GET / (108.61.177.156) 2.56ms
[W 170430 23:06:22 web:2063] 404 GET /css/reset.css (108.61.177.156) 0.56ms
[W 170430 23:06:22 web:2063] 404 GET /css/common.css (108.61.177.156) 0.56ms
[W 170430 23:06:22 web:2063] 404 GET /css/index.css (108.61.177.156) 0.41ms

It means that the browser got the index.html but couldn't get those css files.

So i'm thinking that I need to do something like this:

self.render("frontend/*")

I've tried like this but failed.

Also, if I do need some kind of regular expression to do this, I think it's very dangerous, because user could do such a request from his browser:

www.mysite.com/../../someLocalFileOfServer


Solution

  • Did you read the document of tornado? Just check this document for static serving. http://www.tornadoweb.org/en/stable/guide/running.html#static-files-and-aggressive-file-caching

    Update

    why will it be dangerous? Suppose you have a project like this:

    project
    --static_dir
    ----test.js
    ----some other static files
    --view
    ----index.html
    ----some other view files
    --server.py
    

    you can set your static dir to static_dir, and then the user will have access to test.js by url domian/test.js. So what the user has access to is decided by you.