Skip to content
Myr

Added lazyloading pattern and explicit chapter links in tutorial.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This fixes #49.

authored by Armin Ronacher · committed by Armin Ronacher · parent 6c095de · Browse files · 15 files+146 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+146 added−2 removed

  • other:+146 added−2 removed

15 files+146 added−2 removed

modified:docs/patterns/index.rst+1 added
26 unmodified lines
27 templateinheritance28 flashing29 jquery30 errorpages31 lazyloading
added:docs/patterns/lazyloading.rst+104 added
1Lazily 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 AppEngine 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 the centralized approach you would have one file with the views36(`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 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::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 do 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 propery on the first104request. The same goes for any kind of remaining decorator.
modified:docs/tutorial/css.rst+4 added
1.. _tutorial-css:23Step 7: Adding Style4====================56Now that everything else works, it's time to add some style to the
19 unmodified lines
26 margin-bottom: 1em; background: #fafafa; }27 .flash { background: #CEE5F5; padding: 0.5em;28 border: 1px solid #AACBE2; }29 .error { background: #F0D6D6; padding: 0.5em; }3031Continue with :ref:`tutorial-testing`.
modified:docs/tutorial/dbcon.rst+4 added
1.. _tutorial-dbcon:23Step 4: Request Database Connections4------------------------------------56Now we know how we can open database connections and use them for scripts,
25 unmodified lines
32request only and is available from within each function. Never store such33things on other objects because this would not work with threaded34environments. That special :data:`~flask.g` object does some magic behind35the scenes to ensure it does the right thing.3637Continue to :ref:`tutorial-views`.
modified:docs/tutorial/dbinit.rst+4 added
1.. _tutorial-dbinit:23Step 3: Creating The Database4=============================56Flaskr is a database powered application as outlined earlier, and more
55 unmodified lines
6263 If you get an exception later that a table cannot be found check that64 you did call the `init_db` function and that your table names are65 correct (singular vs. plural for example).6667Continue with :ref:`tutorial-dbcon`
modified:docs/tutorial/folders.rst+4 added
1.. _tutorial-folders:23Step 0: Creating The Folders4============================56Before we get started, let's create the folders needed for this
10 unmodified lines
17This is the place where css and javascript files go. Inside the18`templates` folder Flask will look for `Jinja2`_ templates. Drop all the19templates there.2021Continue with :ref:`tutorial-schema`.2223.. _Jinja2: http://jinja.pocoo.org/2/
modified:docs/tutorial/introduction.rst+4 added
1.. _tutorial-introduction:23Introducing Flaskr4==================56We will call our blogging application flaskr here, feel free to chose a
20 unmodified lines
27 :align: center28 :class: screenshot29 :alt: screenshot of the final application3031Continue with :ref:`tutorial-folders`.3233.. _SQLAlchemy: http://www.sqlalchemy.org/
modified:docs/tutorial/schema.rst+4 added
1.. _tutorial-schema:23Step 1: Database Schema4=======================56First we want to create the database schema. For this application only a
13 unmodified lines
20This schema consists of a single table called `entries` and each row in21this table has an `id`, a `title` and a `text`. The `id` is an22automatically incrementing integer and a primary key, the other two are23strings that must not be null.2425Continue with :ref:`tutorial-setup`.
modified:docs/tutorial/setup.rst+4 added
1.. _tutorial-setup:23Step 2: Application Setup Code4==============================56Now that we have the schema in place we can create the application module.
56 unmodified lines
6364 Want your server to be publically available? Check out the65 :ref:`externally visible server <public-server>` section for more66 information.6768Continue with :ref:`tutorial-dbinit`.
modified:docs/tutorial/templates.rst+4 added
1.. _tutorial-templates:23Step 6: The Templates4=====================56Now we should start working on the templates. If we request the URLs now
99 unmodified lines
106 <dd><input type=submit value=Login>107 </dl>108 </form>109 {% endblock %}110111Continue with :ref:`tutorial-css`.
modified:docs/tutorial/testing.rst+2 added
1.. _tutorial-testing:23Bonus: Testing the Application4===============================56Now that you have finished the application and everything works as
4 unmodified lines
modified:docs/tutorial/views.rst+4 added
1.. _tutorial-views:23Step 5: The View Functions4==========================56Now that the database connections are working we can start writing the
79 unmodified lines
86 def logout():87 session.pop('logged_in', None)88 flash('You were logged out')89 return redirect(url_for('show_entries'))9091Continue with :ref:`tutorial-templates`.
modified:docs/_themesnot shown

Its text is not shown, modified.

modified:docs/conf.py+2 added-2 removed
138 unmodified lines
139# template names.140#html_additional_pages = {}141142# If false, no module index is generated.143#html_use_modindex = True143html_use_modindex = False144145# If false, no index is generated.146#html_use_index = True147
3 unmodified lines
151# If true, links to the reST sources are added to the pages.152#html_show_sourcelink = True153154# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.155#html_show_sphinx = True155html_show_sphinx = False156157# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.158#html_show_copyright = True159
82 unmodified lines
modified:examples/minitwit/minitwit.py+1 added
125 unmodified lines
126 followed = query_db('''select 1 from follower where127 follower.who_id = ? and follower.whom_id = ?''',128 [session['user_id'], profile_user['user_id']],129 one=True) is not None130 broken_just_for_djangocon131 return render_template('timeline.html', messages=query_db('''132 select message.*, user.* from message, user where133 user.user_id = message.author_id and user.user_id = ?134 order by message.pub_date desc limit ?''',
116 unmodified lines