lazyloading.rst
This file
Path
docs/patterns/lazyloading.rst
104 lines · 3.6 KiB
Last changed by
Merge pull request #1247 from Winnetou/patch-8Markus Unterwaditzerbefore adoptionb24438b
History of this fileTake it
The walk stopped after 200 commits: lines older than e562acf point at it.
Set release date for 0.10.1Armin Ronacherbefore adoptione562acf
lines 1–34why, one step back1Lazily Loading Views2====================34Flask is usually used with the decorators. Decorators are simple and you5have the URL right next to the function that is called for that specific6URL. However there is a downside to this approach: it means all your code7that uses decorators has to be imported upfront or Flask will never8actually find your function.910This can be a problem if your application has to import quick. It might11have to do that on systems like Google's App Engine or other systems. So12if you suddenly notice that your application outgrows this approach you13can fall back to a centralized URL mapping.1415The system that enables having a central URL map is the16:meth:`~flask.Flask.add_url_rule` function. Instead of using decorators,17you have a file that sets up the application with all URLs.1819Converting to Centralized URL Map20---------------------------------2122Imagine the current application looks somewhat like this::2324 from flask import Flask25 app = Flask(__name__)2627 @app.route('/')28 def index():29 pass3031 @app.route('/user/<username>')32 def user(username):33 pass34Merge pull request #1247 from Winnetou/patch-8Markus Unterwaditzerbefore adoptionb24438b
line 35why, one step back35Then, with the centralized approach you would have one file with the viewsMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 36why, one step back36(:file:`views.py`) but without any decorator::Set release date for 0.10.1Armin Ronacherbefore adoptione562acf
lines 37–56why, one step back3738 def index():39 pass4041 def user(username):42 pass4344And then a file that sets up an application which maps the functions to45URLs::4647 from flask import Flask48 from yourapplication import views49 app = Flask(__name__)50 app.add_url_rule('/', view_func=views.index)51 app.add_url_rule('/user/<username>', view_func=views.user)5253Loading Late54------------5556So far we only split up the views and the routing, but the module is stillMerge pull request #1247 from Winnetou/patch-8Markus Unterwaditzerbefore adoptionb24438b
line 57why, one step back57loaded upfront. The trick is to actually load the view function as needed.Set release date for 0.10.1Armin Ronacherbefore adoptione562acf
lines 58–104why, one step back58This can be accomplished with a helper class that behaves just like a59function but internally imports the real function on first use::6061 from werkzeug import import_string, cached_property6263 class LazyView(object):6465 def __init__(self, import_name):66 self.__module__, self.__name__ = import_name.rsplit('.', 1)67 self.import_name = import_name6869 @cached_property70 def view(self):71 return import_string(self.import_name)7273 def __call__(self, *args, **kwargs):74 return self.view(*args, **kwargs)7576What's important here is is that `__module__` and `__name__` are properly77set. This is used by Flask internally to figure out how to name the78URL rules in case you don't provide a name for the rule yourself.7980Then you can define your central place to combine the views like this::8182 from flask import Flask83 from yourapplication.helpers import LazyView84 app = Flask(__name__)85 app.add_url_rule('/',86 view_func=LazyView('yourapplication.views.index'))87 app.add_url_rule('/user/<username>',88 view_func=LazyView('yourapplication.views.user'))8990You can further optimize this in terms of amount of keystrokes needed to91write this by having a function that calls into92:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93name and a dot, and by wrapping `view_func` in a `LazyView` as needed::9495 def url(url_rule, import_name, **options):96 view = LazyView('yourapplication.' + import_name)97 app.add_url_rule(url_rule, view_func=view, **options)9899 url('/', 'views.index')100 url('/user/<username>', 'views.user')101102One thing to keep in mind is that before and after request handlers have103to be in a file that is imported upfront to work properly on the first104request. The same goes for any kind of remaining decorator.