pythonwebob

I want to serve files from a folder with webob


I want to use webob.static.DirectoryApp. I just can't figure out how to do it:

From the example at http://docs.webob.org/en/latest/file-example.html my router looks like:

class Router(object):
    def __init__(self, static_path=None):
        self.routes = []
        self.static_path = static_path if static_path is not None else os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
        self.static_app = DirectoryApp(self.static_path)

    def add_route(self, template, controller, **vars):
        if isinstance(controller, basestring):
            controller = load_controller(controller)
        self.routes.append((re.compile(template_to_regex(template)),
                            controller,
                            vars))

    def __call__(self, environ, start_response):
        req = Request(environ)
        for regex, controller, vars in self.routes:
            match = regex.match(req.path_info)
            if match:
                req.urlvars = match.groupdict()
                req.urlvars.update(vars)
                return controller(environ, start_response)

        return exc.HTTPNotFound()(environ, start_response)

To create the application to serve:

def create_app():
    router = Router()

    #router.add_route('/', controller='app.controllers.default:index')
    router.add_route('/', controller=default.index)

    return router

This serves routes to my added controllers fine. I also added a self.static_app.

I just have no idea how to use it to serve static files from the static-folder! Can someone please enlighten me?


Solution

  • As @gawel wrote the answer is to add a route with DirectoryApp as the controller. There is another thing to notice for it to work directly from the example.

    The extension template_to_regex in the example is adding a $ to the forcing us to write a route expression that covers the entire url to catch. The canbewhatever is never used and can be whatever. The important thing is the regex after the variable.

    The add_route should look something like this:

    router.add_route('/static{canbewhatever:.*}', controller=static_app)