Falcon: Django-like urlreverse router

The default Falcon router don't support urlreverse, but fortunately it allows us to use a costomized router.

Override the add_route, adding a aditional params name to specified url template name.

Note: Falcon version should >=0.4 to support this feature.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from falcon.routing import DefaultRouter


class ReverseRouter(DefaultRouter):
    url_map = {}

    # override add_route to add our map
    def add_route(self, uri_template, method_map, resource, name=None):
        if name:
            self.url_map[name] = uri_template
        DefaultRouter.add_route(self, uri_template, method_map, resource)

    def reverse(self, _name, **kwargs):
        '''
        reverse url
        '''
        assert _name in self.url_map, "url name: %s not in url map" % _name
        url_tmpl = self.url_map.get(_name)
        return url_tmpl.format(**kwargs)

then, we can use reverse method to do a Django-like url reverse, here is an example:

1
2
3
4
5
6
7
8
9
10
11
# usage example:
import falcon  # NOQA

router = ReverseRouter()
api = falcon.API(router=router)
# add a router
api.add_route('/user/{name}', 'user_res', name='user')

# reverse url
print (router.reverse('user', name='mike'))
# /user/mike

留言