Skip to content
Myr

lazyloading.rst

This file

Path

docs/patterns/lazyloading.rst

109 lines · 3.8 KiB

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

The walk stopped after 200 commits: lines older than 817b72d point at it.

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

lines 1–34why, one step back
1Lazily Loading Views
2====================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 pass34

Merge pull request #1247 from Winnetou/patch-8Markus Unterwaditzerbefore adoptionb24438b

line 35why, one step back
35Then, with the centralized approach you would have one file with the views

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 36why, one step back
36(:file:`views.py`) but without any decorator::

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

lines 37–56why, one step back
37
38 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 still

Merge pull request #1247 from Winnetou/patch-8Markus Unterwaditzerbefore adoptionb24438b

line 57why, one step back
57loaded upfront. The trick is to actually load the view function as needed.

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

lines 58–92why, one step back
58This can be accomplished with a helper class that behaves just like a
59function 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 project

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 93why, one step back
93name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

line 94why, one step back
94

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 95why, one step back
95 def url(import_name, url_rules=[], **options):

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

line 96why, one step back
96 view = LazyView('yourapplication.' + import_name)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 97–98why, one step back
97 for url_rule in url_rules:
98 app.add_url_rule(url_rule, view_func=view, **options)

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

line 99why, one step back
99

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 100–105why, one step back
100 # add a single route to the index view
101 url('views.index', ['/'])102103 # add two routes to a single function endpoint104 url_rules = ['/user/','/user/<username>']105 url('views.user', url_rules)

Removed deprecated module functionalityArmin Ronacherbefore adoption817b72d

lines 106–109why, one step back
106
107One 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.