Falcon (http://falconframework.org/) is a minimalist Python WSGI web framework for building fast and lightweight APIs. It strongly encourages the REST architectural style that is currently very popular around the web. It is a good alternative to other rather heavy frameworks, such as Django or Pyramid. It is also a strong competitor to other micro-frameworks that aim for simplicity, such as Flask, Bottle, or web2py.
One of its features is it's very simple routing mechanism. It is not as complex as the routing provided by Django urlconf and does not provide as many features, but in most cases is just enough for any API that follows the REST architectural design. What is most interesting about Falcon's routing is the internal construction of that router. Falcon's router is implemented using the code generated from the list of routes, and code changes every time a new route is registered. This is the effort that's needed to make routing fast.
Consider this very short API example, taken from Falcon's web documentation:
# sample.py import falcon import json class QuoteResource: def on_get(self, req, resp): """Handles GET requests""" quote = { 'quote': 'I\'ve always been more interested in ' 'the future than in the past.', 'author': 'Grace Hopper' } resp.body = json.dumps(quote) api = falcon.API() api.add_route('/quote', QuoteResource())
In short, the highlighted call to the api.add_route() method updates dynamically the whole generated code tree for Falcon's request router. It also compiles it using the compile() function and generates the new route-finding function using eval(). Let's take a closer look at the following __code__ attribute of the api._router._find() function:
>>> api._router._find.__code__ <code object find at 0x00000000033C29C0, file "<string>", line 1> >>> api.add_route('/none', None) >>> api._router._find.__code__ <code object find at 0x00000000033C2810, file "<string>", line 1>
This transcript shows that the code of this function was generated from the string and not from the real source code file (the "<string>" file). It also shows that the actual code object changes with every call to the api.add_route() method (the object's address in memory changes).