Lazily Loading Views
This can be a problem if your application has to import quick. It mighthave to do that on systems like Google’s App Engine or other systems. Soif you suddenly notice that your application outgrows this approach youcan fall back to a centralized URL mapping.
The system that enables having a central URL map is the function. Instead of using decorators,you have a file that sets up the application with all URLs.
Then, with the centralized approach you would have one file with the views() but without any decorator:
- def index():
- pass
- def user(username):
- pass
And then a file that sets up an application which maps the functions toURLs:
Loading Late
- from werkzeug import import_string, cached_property
- class LazyView(object):
- def __init__(self, import_name):
- self.__module__, self.__name__ = import_name.rsplit('.', 1)
- self.import_name = import_name
- @cached_property
- def view(self):
- return import_string(self.import_name)
- def __call__(self, *args, **kwargs):
- return self.view(*args, **kwargs)
What’s important here is is that module and name are properlyset. This is used by Flask internally to figure out how to name theURL rules in case you don’t provide a name for the rule yourself.
Then you can define your central place to combine the views like this:
- view = LazyView('yourapplication.' + import_name)
- for url_rule in url_rules:
- app.add_url_rule(url_rule, view_func=view, **options)
- # add a single route to the index view
- url('views.index', ['/'])
- # add two routes to a single function endpoint
- url_rules = ['/user/','/user/<username>']
- url('views.user', url_rules)
One thing to keep in mind is that before and after request handlers haveto be in a file that is imported upfront to work properly on the firstrequest. The same goes for any kind of remaining decorator.