lazyloading.rst
This file
Path
docs/patterns/lazyloading.rst
109 lines · 3.8 KiB
Last changed by
Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
History of this fileTake it
The walk stopped after 200 commits: lines older than 4f3dbb3 point at it.
Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 1–60why, 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 pass3435Then, with the centralized approach you would have one file with the views36(:file:`views.py`) but without any decorator::3738 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 still57loaded upfront. The trick is to actually load the view function as needed.58This can be accomplished with a helper class that behaves just like a59function but internally imports the real function on first use::60Merge branch '1.1.x'David Lordbefore adoption40eadfc
line 61why, one step back61 from werkzeug.utils import import_string, cached_propertyMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 62–95why, one step back6263 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(import_name, url_rules=[], **options):Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 96why, one step back96 view = LazyView(f"yourapplication.{import_name}")Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 97–109why, one step back97 for url_rule in url_rules:98 app.add_url_rule(url_rule, view_func=view, **options)99100 # add a single route to the index view101 url('views.index', ['/'])102103 # add two routes to a single function endpoint104 url_rules = ['/user/','/user/<username>']105 url('views.user', url_rules)106107One thing to keep in mind is that before and after request handlers have108to be in a file that is imported upfront to work properly on the first109request. The same goes for any kind of remaining decorator.