Search code examples
tornado

Tornado StaticFileHandler path for multiple regex capture group


From an URL of the form: /foo/(.*)/bar/(.*) , I want to serve files, where the actual path is computed from the 2 captured groups. My problem is that StaticFileHandler's get() takes only 1 path parameter. Is there a way to get this to work, without having to reimplement most of StaticFileHandler's methods ?

My current workaround is to capture everything: (/foo/.*/bar/.*) , but then I have to reparse a similar regex inside an overriden get_absolute_path().


Solution

  • There is no way to do that without extending StaticFileHandler. It would be a tiny change:

    from tornado import gen, web
    
    class CustomStaticFileHandler(web.StaticFileHandler):
    
        def get(self, part1, part2, include_body=True):
            # mangle path
            path = "dome_{}_combined_path_{}".format(part1, part2)
            # back to staticfilehandler
            return super().get(path, include_body)
    
        # if you need to use coroutines on mangle use 
        #
        # @gen.coroutine
        # def get(self, part1, part2, include_body=True):
        #     path = yield some_db.get_path(part1, part2)
        #     yield super().get(path, include_body)
    
    app = web.Application([
        (r"/foo/(.*)/bar/(.*)", CustomStaticFileHandler, {"path": "/tmp"}),
    ])