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
Provenance
- Commit
9d19b77- Tree
a109fcd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6c095de
15 files changed+146 added−2 removed
modified:docs/patterns/index.rst+1 added
26 unmodified lines27 templateinheritance28 flashing29 jquery30 errorpages31+ lazyloadingadded:docs/patterns/lazyloading.rst+104 added
1+Lazily Loading Views2+====================3+4+Flask is usually used with the decorators. Decorators are simple and you5+have the URL right next to the function that is called for that specific6+URL. However there is a downside to this approach: it means all your code7+that uses decorators has to be imported upfront or Flask will never8+actually find your function.9+10+This can be a problem if your application has to import quick. It might11+have to do that on systems like Google's AppEngine or other systems. So12+if you suddenly notice that your application outgrows this approach you13+can fall back to a centralized URL mapping.14+15+The system that enables having a central URL map is the16+:meth:`~flask.Flask.add_url_rule` function. Instead of using decorators,17+you have a file that sets up the application with all URLs.18+19+Converting to Centralized URL Map20+---------------------------------21+22+Imagine the current application looks somewhat like this::23+24+ from flask import Flask25+ app = Flask(__name__)26+27+ @app.route('/')28+ def index():29+ pass30+31+ @app.route('/user/<username>')32+ def user(username):33+ pass34+35+Then the centralized approach you would have one file with the views36+(`views.py`) but without any decorator::37+38+ def index():39+ pass40+41+ def user(username):42+ pass43+44+And then a file that sets up an application which maps the functions to45+URLs::46+47+ 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)52+53+Loading Late54+------------55+56+So far we only split up the views and the routing, but the module is still57+loaded upfront. The trick to actually load the view function as needed.58+This can be accomplished with a helper class that behaves just like a59+function but internally imports the real function on first use::60+61+ from werkzeug import import_string, cached_property62+63+ class LazyView(object):64+65+ def __init__(self, import_name):66+ self.__module__, self.__name__ = import_name.rsplit('.', 1)67+ self.import_name = import_name68+69+ @cached_property70+ def view(self):71+ return import_string(self.import_name)72+73+ def __call__(self, *args, **kwargs):74+ return self.view(*args, **kwargs)75+76+What's important here is is that `__module__` and `__name__` are properly77+set. This is used by Flask internally to figure out how to do name the78+URL rules in case you don't provide a name for the rule yourself.79+80+Then you can define your central place to combine the views like this::81+82+ 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'))89+90+You can further optimize this in terms of amount of keystrokes needed to91+write this by having a function that calls into92+:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93+name and a dot, and by wrapping `view_func` in a `LazyView` as needed::94+95+ def url(url_rule, import_name, **options):96+ view = LazyView('yourapplication.' + import_name)97+ app.add_url_rule(url_rule, view_func=view, **options)98+99+ url('/', 'views.index')100+ url('/user/<username>', 'views.user')101+102+One thing to keep in mind is that before and after request handlers have103+to be in a file that is imported upfront to work propery on the first104+request. The same goes for any kind of remaining decorator.modified:docs/tutorial/css.rst+4 added
1+.. _tutorial-css:2+3 Step 7: Adding Style4 ====================5 6 Now that everything else works, it's time to add some style to the19 unmodified lines26 margin-bottom: 1em; background: #fafafa; }27 .flash { background: #CEE5F5; padding: 0.5em;28 border: 1px solid #AACBE2; }29 .error { background: #F0D6D6; padding: 0.5em; }30+31+Continue with :ref:`tutorial-testing`.modified:docs/tutorial/dbcon.rst+4 added
1+.. _tutorial-dbcon:2+3 Step 4: Request Database Connections4 ------------------------------------5 6 Now we know how we can open database connections and use them for scripts,25 unmodified lines32 request only and is available from within each function. Never store such33 things on other objects because this would not work with threaded34 environments. That special :data:`~flask.g` object does some magic behind35 the scenes to ensure it does the right thing.36+37+Continue to :ref:`tutorial-views`.modified:docs/tutorial/dbinit.rst+4 added
1+.. _tutorial-dbinit:2+3 Step 3: Creating The Database4 =============================5 6 Flaskr is a database powered application as outlined earlier, and more55 unmodified lines62 63 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).66+67+Continue with :ref:`tutorial-dbcon`modified:docs/tutorial/folders.rst+4 added
1+.. _tutorial-folders:2+3 Step 0: Creating The Folders4 ============================5 6 Before we get started, let's create the folders needed for this10 unmodified lines17 This is the place where css and javascript files go. Inside the18 `templates` folder Flask will look for `Jinja2`_ templates. Drop all the19 templates there.20 21+Continue with :ref:`tutorial-schema`.22+23 .. _Jinja2: http://jinja.pocoo.org/2/modified:docs/tutorial/introduction.rst+4 added
1+.. _tutorial-introduction:2+3 Introducing Flaskr4 ==================5 6 We will call our blogging application flaskr here, feel free to chose a20 unmodified lines27 :align: center28 :class: screenshot29 :alt: screenshot of the final application30 31+Continue with :ref:`tutorial-folders`.32+33 .. _SQLAlchemy: http://www.sqlalchemy.org/modified:docs/tutorial/schema.rst+4 added
1+.. _tutorial-schema:2+3 Step 1: Database Schema4 =======================5 6 First we want to create the database schema. For this application only a13 unmodified lines20 This schema consists of a single table called `entries` and each row in21 this table has an `id`, a `title` and a `text`. The `id` is an22 automatically incrementing integer and a primary key, the other two are23 strings that must not be null.24+25+Continue with :ref:`tutorial-setup`.modified:docs/tutorial/setup.rst+4 added
1+.. _tutorial-setup:2+3 Step 2: Application Setup Code4 ==============================5 6 Now that we have the schema in place we can create the application module.56 unmodified lines63 64 Want your server to be publically available? Check out the65 :ref:`externally visible server <public-server>` section for more66 information.67+68+Continue with :ref:`tutorial-dbinit`.modified:docs/tutorial/templates.rst+4 added
1+.. _tutorial-templates:2+3 Step 6: The Templates4 =====================5 6 Now we should start working on the templates. If we request the URLs now99 unmodified lines106 <dd><input type=submit value=Login>107 </dl>108 </form>109 {% endblock %}110+111+Continue with :ref:`tutorial-css`.modified:docs/tutorial/testing.rst+2 added
1+.. _tutorial-testing:2+3 Bonus: Testing the Application4 ===============================5 6 Now that you have finished the application and everything works as4 unmodified linesmodified:docs/tutorial/views.rst+4 added
1+.. _tutorial-views:2+3 Step 5: The View Functions4 ==========================5 6 Now that the database connections are working we can start writing the79 unmodified lines86 def logout():87 session.pop('logged_in', None)88 flash('You were logged out')89 return redirect(url_for('show_entries'))90+91+Continue with :ref:`tutorial-templates`.modified:docs/_themesnot shown
Its text is not shown, modified.
modified:docs/conf.py+2 added-2 removed
138 unmodified lines139 # template names.140 #html_additional_pages = {}141 142 # If false, no module index is generated.143-#html_use_modindex = True143+html_use_modindex = False144 145 # If false, no index is generated.146 #html_use_index = True147 3 unmodified lines151 # If true, links to the reST sources are added to the pages.152 #html_show_sourcelink = True153 154 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.155-#html_show_sphinx = True155+html_show_sphinx = False156 157 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.158 #html_show_copyright = True159 82 unmodified linesmodified:examples/minitwit/minitwit.py+1 added
125 unmodified lines126 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