Breaking docs up into smaller pieces
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 764b4e4 · Browse files · 8 files·+443 added−445 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+443 added−445 removed
- other:+443 added−445 removed
Provenance
- Commit
123a1ad- Tree
d1687f9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
764b4e4
8 files changed+443 added−445 removed
added:docs/patterns/flashing.rst+79 added
1+Message Flashing2+================3+4+Good applications and user interfaces are all about feedback. If the user5+does not get enough feedback he will probably end up hating the6+application. Flask provides a really simple way to give feedback to a7+user with the flashing system. The flashing system basically makes it8+possible to record a message at the end of a request and access it next9+request and only next request. This is usually combined with a layout10+template that does this.11+12+So here a full example::13+14+ from flask import flash, redirect, url_for, render_template15+16+ @app.route('/')17+ def index():18+ return render_template('index.html')19+20+ @app.route('/login', methods=['GET', 'POST'])21+ def login():22+ error = None23+ if request.method == 'POST':24+ if request.form['username'] != 'admin' or \25+ request.form['password'] != 'secret':26+ error = 'Invalid credentials'27+ else:28+ flash('You were sucessfully logged in')29+ return redirect(url_for('index'))30+ return render_template('login.html', error=error)31+32+And here the ``layout.html`` template which does the magic:33+34+.. sourcecode:: html+jinja35+36+ <!doctype html>37+ <title>My Application</title>38+ {% with messages = get_flashed_messages() %}39+ {% if messages %}40+ <ul class=flashes>41+ {% for message in messages %}42+ <li>{{ message }}</li>43+ {% endfor %}44+ </ul>45+ {% endif %}46+ {% endwith %}47+ {% block body %}{% endblock %}48+49+And here the index.html template:50+51+.. sourcecode:: html+jinja52+53+ {% extends "layout.html" %}54+ {% block body %}55+ <h1>Overview</h1>56+ <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>57+ {% endblock %}58+59+And of course the login template:60+61+.. sourcecode:: html+jinja62+63+ {% extends "layout.html" %}64+ {% block body %}65+ <h1>Login</h1>66+ {% if error %}67+ <p class=error><strong>Error:</strong> {{ error }}68+ {% endif %}69+ <form action="" method=post>70+ <dl>71+ <dt>Username:72+ <dd><input type=text name=username value="{{73+ request.form.username }}">74+ <dt>Password:75+ <dd><input type=password name=password>76+ </dl>77+ <p><input type=submit value=Login>78+ </form>79+ {% endblock %}added:docs/patterns/index.rst+20 added
1+.. _patterns:2+3+Patterns for Flask4+==================5+6+Certain things are common enough that the changes are high you will find7+them in most web applications. For example quite a lot of applications8+are using relational databases and user authentication. In that case,9+changes are they will open a database connection at the beginning of the10+request and get the information of the currently logged in user. At the11+end of the request, the database connection is closed again.12+13+.. toctree::14+ :maxdepth: 215+16+ packages17+ sqlite318+ sqlalchemy19+ templateinheritance20+ flashingadded:docs/patterns/packages.rst+87 added
1+.. _larger-applications:2+3+Larger Applications4+===================5+6+For larger applications it's a good idea to use a package instead of a7+module. That is quite simple. Imagine a small application looks like8+this::9+10+ /yourapplication11+ /yourapplication.py12+ /static13+ /style.css14+ /templates15+ layout.html16+ index.html17+ login.html18+ ...19+20+To convert that into a larger one, just create a new folder21+`yourapplication` inside the existing one and move everything below it.22+Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete23+all `.pyc` files first, otherwise things would most likely break)24+25+You should then end up with something like that::26+27+ /yourapplication28+ /yourapplication29+ /__init__.py30+ /static31+ /style.css32+ /templates33+ layout.html34+ index.html35+ login.html36+ ...37+38+But how do you run your application now? The naive ``python39+yourapplication/__init__.py`` will not work. Let's just say that Python40+does not want modules in packages to be the startup file. But that is not41+a big problem, just add a new file called `runserver.py` next to the inner42+`yourapplication` folder with the following contents::43+44+ from yourapplication import app45+ app.run(debug=True)46+47+What did we gain from this? Now we can restructure the application a bit48+into multiple modules. The only thing you have to remember is the49+following quick checklist:50+51+1. the `Flask` application object creation have to be in the52+ `__init__.py` file. That way each module can import it safely and the53+ `__name__` variable will resole to the correct package.54+2. all the view functions (the ones with a :meth:`~flask.Flask.route`55+ decorator on top) have to be imported when in the `__init__.py` file.56+ Not the objects itself, but the module it is in. Do the importing at57+ the *bottom* of the file.58+59+Here an example `__init__.py`::60+61+ from flask import Flask62+ app = Flask(__name__)63+64+ import yourapplication.views65+66+And this is what `views.py` would look like::67+68+ from yourapplication import app69+70+ @app.route('/')71+ def index():72+ return 'Hello World!'73+74+.. admonition:: Circular Imports75+76+ Every Python programmer hates them, and yet we just added some:77+ circular imports (That's when two module depend on each one. In this78+ case `views.py` depends on `__init__.py`). Be advised that this is a79+ bad idea in general but here it is actually fine. The reason for this80+ is81+ that we are not actually using the views in `__init__.py` and just82+ ensuring the module is imported and we are doing that at the bottom of83+ the file.84+85+ There are still some problems with that approach but if you want to use86+ decorators there is no way around that. Check out the87+ :ref:`becomingbig` section for some inspiration how to deal with that.added:docs/patterns/sqlalchemy.rst+100 added
1+.. _sqlalchemy-pattern:2+3+SQLAlchemy in Flask4+===================5+6+Many people prefer `SQLAlchemy`_ for database access. In this case it's7+encouraged to use a package instead of a module for your flask application8+and drop the models into a separate module (:ref:`larger-applications`).9+Although that is not necessary but makes a lot of sense.10+11+There are three very common ways to use SQLAlchemy. I will outline each12+of them here:13+14+Declarative15+-----------16+17+The declarative extension in SQLAlchemy is the most recent method of using18+SQLAlchemy. It allows you to define tables and models in one go, similar19+to how Django works. In addition to the following text I recommend the20+official documentation on the `declarative`_ extension.21+22+Here the example `database.py` module for your application::23+24+ from sqlalchemy import create_engine25+ from sqlalchemy.orm import scoped_session, sessionmaker26+ from sqlalchemy.ext.declarative import declarative_base27+28+ engine = create_engine('sqlite:////tmp/test.db')29+ db_session = scoped_session(sessionmaker(autocommit=False,30+ autoflush=False,31+ bind=engine)) 32+ Base = declarative_base()33+ Base.query = db_session.query_property()34+35+ def init_db():36+ Base.metadata.create_all(bind=engine)37+38+To define your models, just subclass the `Base` class that was created by39+the code above. If you are wondering why we don't have to care about40+threads here (like we did in the SQLite3 example above with the41+:data:`~flask.g` object): that's because SQLAlchemy does that for us42+already with the :class:`~sqlalchemy.orm.scoped_session`.43+44+To use SQLAlchemy in a declarative way with your application, you just45+have to put the following code into your application module. Flask will46+automatically remove database sessions at the end of the request for you::47+48+ from yourapplication.database import db_session49+50+ @app.after_request51+ def shutdown_session(response):52+ db_session.remove()53+ return response54+55+Here an example model (put that into `models.py` for instance)::56+57+ from sqlalchemy import Column, Integer, String58+ from yourapplication.database import Base59+60+ class User(Base):61+ __tablename__ = 'users'62+ id = Column(Integer, primary_key=True)63+ name = Column(String(50), unique=True)64+ email = Column(String(120), unique=True)65+66+ def __init__(self, name=None, email=None):67+ self.name = name68+ self.email = email69+70+ def __repr__(self):71+ return '<User %r>' % (self.name, self.email)72+73+You can insert entries into the database like this then:74+75+>>> from yourapplication.database import db_session76+>>> from yourapplication.models import User77+>>> u = User('admin', 'admin@localhost')78+>>> db_session.add(u)79+>>> db_session.commit()80+81+Querying is simple as well:82+83+>>> User.query.all()84+[<User u'admin'>]85+>>> User.query.filter(User.name == 'admin').first()86+<User u'admin'>87+88+.. _SQLAlchemy: http://www.sqlalchemy.org/89+.. _declarative:90+ http://www.sqlalchemy.org/docs/reference/ext/declarative.html91+92+Manual Object Relational Mapping93+--------------------------------94+95+*coming soon*96+97+SQL Abstraction Layer98+---------------------99+100+*coming soon*added:docs/patterns/sqlite3.rst+87 added
1+.. _sqlite3:2+3+Using SQLite 3 with Flask4+=========================5+6+In Flask you can implement opening of dabase connections at the beginning7+of the request and closing at the end with the8+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`9+decorators in combination with the special :class:`~flask.g` object.10+11+So here a simple example how you can use SQLite 3 with Flask::12+13+ import sqlite314+ from flask import g15+16+ DATABASE = '/path/to/database.db'17+18+ def connect_db():19+ return sqlite3.connect(DATABASE)20+21+ @app.before_request22+ def before_request():23+ g.db = connect_db()24+25+ @app.after_request26+ def after_request(response):27+ g.db.close()28+ return response29+30+.. _easy-querying:31+32+Easy Querying33+-------------34+35+Now in each request handling function you can access `g.db` to get the36+current open database connection. To simplify working with SQLite a37+helper function can be useful::38+39+ def query_db(query, args=(), one=False):40+ cur = g.db.execute(query, args)41+ rv = [dict((cur.description[idx][0], value)42+ for idx, value in enumerate(row)) for row in cur.fetchall()]43+ return (rv[0] if rv else None) if one else rv44+45+This handy little function makes working with the database much more46+pleasant than it is by just using the raw cursor and connection objects.47+48+Here is how you can use it::49+50+ for user in query_db('select * from users'):51+ print user['username'], 'has the id', user['user_id']52+53+Or if you just want a single result::54+55+ user = query_db('select * from users where username = ?',56+ [the_username], one=True)57+ if user is None:58+ print 'No such user'59+ else:60+ print the_username, 'has the id', user['user_id']61+62+To pass variable parts to the SQL statement, use a question mark in the63+statement and pass in the arguments as a list. Never directly add them to64+the SQL statement with string formattings because this makes it possible65+to attack the application using `SQL Injections66+<http://en.wikipedia.org/wiki/SQL_injection>`_.67+68+Initial Schemas69+---------------70+71+Relational databases need schemas, so applications often ship a72+`schema.sql` file that creates the database. It's a good idea to provide73+a function that creates the database bases on that schema. This function74+can do that for you::75+76+ from contextlib import closing77+ 78+ def init_db():79+ with closing(connect_db()) as db:80+ with app.open_resource('schema.sql') as f:81+ db.cursor().executescript(f.read())82+ db.commit()83+84+You can then create such a database from the python shell:85+86+>>> from yourapplication import init_db87+>>> init_db()added:docs/patterns/templateinheritance.rst+69 added
1+.. _template-inheritance:2+3+Template Inheritance4+====================5+6+The most powerful part of Jinja is template inheritance. Template inheritance7+allows you to build a base "skeleton" template that contains all the common8+elements of your site and defines **blocks** that child templates can override.9+10+Sounds complicated but is very basic. It's easiest to understand it by starting11+with an example.12+13+14+Base Template15+-------------16+17+This template, which we'll call ``layout.html``, defines a simple HTML skeleton18+document that you might use for a simple two-column page. It's the job of19+"child" templates to fill the empty blocks with content:20+21+.. sourcecode:: html+jinja22+23+ <!doctype html>24+ <html>25+ <head>26+ {% block head %}27+ <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">28+ <title>{% block title %}{% endblock %} - My Webpage</title>29+ {% endblock %}30+ </head>31+ <body>32+ <div id="content">{% block content %}{% endblock %}</div>33+ <div id="footer">34+ {% block footer %}35+ © Copyright 2010 by <a href="http://domain.invalid/">you</a>.36+ {% endblock %}37+ </div>38+ </body>39+40+In this example, the ``{% block %}`` tags define four blocks that child templates41+can fill in. All the `block` tag does is to tell the template engine that a42+child template may override those portions of the template.43+44+Child Template45+--------------46+47+A child template might look like this:48+49+.. sourcecode:: html+jinja50+51+ {% extends "layout.html" %}52+ {% block title %}Index{% endblock %}53+ {% block head %}54+ {{ super() }}55+ <style type="text/css">56+ .important { color: #336699; }57+ </style>58+ {% endblock %}59+ {% block content %}60+ <h1>Index</h1>61+ <p class="important">62+ Welcome on my awesome homepage.63+ {% endblock %}64+65+The ``{% extends %}`` tag is the key here. It tells the template engine that66+this template "extends" another template. When the template system evaluates67+this template, first it locates the parent. The extends tag must be the68+first tag in the template. To render the contents of a block defined in69+the parent template, use ``{{ super() }}``.modified:docs/index.rst+1 added-1 removed
38 unmodified lines39 installation40 quickstart41 tutorial/index42 testing43- patterns43+ patterns/index44 deploying45 becomingbig46 47 Reference9 unmodified linesdeleted:docs/patterns.rst-444 removed
1-.. _patterns:2-3-Patterns for Flask4-==================5-6-Certain things are common enough that the changes are high you will find7-them in most web applications. For example quite a lot of applications8-are using relational databases and user authentication. In that case,9-changes are they will open a database connection at the beginning of the10-request and get the information of the currently logged in user. At the11-end of the request, the database connection is closed again.12-13-14-.. _larger-applications:15-16-Larger Applications17--------------------18-19-For larger applications it's a good idea to use a package instead of a20-module. That is quite simple. Imagine a small application looks like21-this::22-23- /yourapplication24- /yourapplication.py25- /static26- /style.css27- /templates28- layout.html29- index.html30- login.html31- ...32-33-To convert that into a larger one, just create a new folder34-`yourapplication` inside the existing one and move everything below it.35-Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete36-all `.pyc` files first, otherwise things would most likely break)37-38-You should then end up with something like that::39-40- /yourapplication41- /yourapplication42- /__init__.py43- /static44- /style.css45- /templates46- layout.html47- index.html48- login.html49- ...50-51-But how do you run your application now? The naive ``python52-yourapplication/__init__.py`` will not work. Let's just say that Python53-does not want modules in packages to be the startup file. But that is not54-a big problem, just add a new file called `runserver.py` next to the inner55-`yourapplication` folder with the following contents::56-57- from yourapplication import app58- app.run(debug=True)59-60-What did we gain from this? Now we can restructure the application a bit61-into multiple modules. The only thing you have to remember is the62-following quick checklist:63-64-1. the `Flask` application object creation have to be in the65- `__init__.py` file. That way each module can import it safely and the66- `__name__` variable will resole to the correct package.67-2. all the view functions (the ones with a :meth:`~flask.Flask.route`68- decorator on top) have to be imported when in the `__init__.py` file.69- Not the objects itself, but the module it is in. Do the importing at70- the *bottom* of the file.71-72-Here an example `__init__.py`::73-74- from flask import Flask75- app = Flask(__name__)76-77- import yourapplication.views78-79-And this is what `views.py` would look like::80-81- from yourapplication import app82-83- @app.route('/')84- def index():85- return 'Hello World!'86-87-.. admonition:: Circular Imports88-89- Every Python programmer hates them, and yet we just added some:90- circular imports (That's when two module depend on each one. In this91- case `views.py` depends on `__init__.py`). Be advised that this is a92- bad idea in general but here it is actually fine. The reason for this93- is94- that we are not actually using the views in `__init__.py` and just95- ensuring the module is imported and we are doing that at the bottom of96- the file.97-98- There are still some problems with that approach but if you want to use99- decorators there is no way around that. Check out the100- :ref:`becomingbig` section for some inspiration how to deal with that.101-102-103-.. _database-pattern:104-105-Using SQLite 3 with Flask106--------------------------107-108-In Flask you can implement opening of dabase connections at the beginning109-of the request and closing at the end with the110-:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`111-decorators in combination with the special :class:`~flask.g` object.112-113-So here a simple example how you can use SQLite 3 with Flask::114-115- import sqlite3116- from flask import g117-118- DATABASE = '/path/to/database.db'119-120- def connect_db():121- return sqlite3.connect(DATABASE)122-123- @app.before_request124- def before_request():125- g.db = connect_db()126-127- @app.after_request128- def after_request(response):129- g.db.close()130- return response131-132-.. _easy-querying:133-134-Easy Querying135-`````````````136-137-Now in each request handling function you can access `g.db` to get the138-current open database connection. To simplify working with SQLite a139-helper function can be useful::140-141- def query_db(query, args=(), one=False):142- cur = g.db.execute(query, args)143- rv = [dict((cur.description[idx][0], value)144- for idx, value in enumerate(row)) for row in cur.fetchall()]145- return (rv[0] if rv else None) if one else rv146-147-This handy little function makes working with the database much more148-pleasant than it is by just using the raw cursor and connection objects.149-150-Here is how you can use it::151-152- for user in query_db('select * from users'):153- print user['username'], 'has the id', user['user_id']154-155-Or if you just want a single result::156-157- user = query_db('select * from users where username = ?',158- [the_username], one=True)159- if user is None:160- print 'No such user'161- else:162- print the_username, 'has the id', user['user_id']163-164-To pass variable parts to the SQL statement, use a question mark in the165-statement and pass in the arguments as a list. Never directly add them to166-the SQL statement with string formattings because this makes it possible167-to attack the application using `SQL Injections168-<http://en.wikipedia.org/wiki/SQL_injection>`_.169-170-Initial Schemas171-```````````````172-173-Relational databases need schemas, so applications often ship a174-`schema.sql` file that creates the database. It's a good idea to provide175-a function that creates the database bases on that schema. This function176-can do that for you::177-178- from contextlib import closing179- 180- def init_db():181- with closing(connect_db()) as db:182- with app.open_resource('schema.sql') as f:183- db.cursor().executescript(f.read())184- db.commit()185-186-You can then create such a database from the python shell:187-188->>> from yourapplication import init_db189->>> init_db()190-191-192-.. _sqlalchemy-pattern:193-194-SQLAlchemy in Flask195--------------------196-197-Many people prefer `SQLAlchemy`_ for database access. In this case it's198-encouraged to use a package instead of a module for your flask application199-and drop the models into a separate module (:ref:`larger-applications`).200-Although that is not necessary but makes a lot of sense.201-202-There are three very common ways to use SQLAlchemy. I will outline each203-of them here:204-205-Declarative206-```````````207-208-The declarative extension in SQLAlchemy is the most recent method of using209-SQLAlchemy. It allows you to define tables and models in one go, similar210-to how Django works. In addition to the following text I recommend the211-official documentation on the `declarative`_ extension.212-213-Here the example `database.py` module for your application::214-215- from sqlalchemy import create_engine216- from sqlalchemy.orm import scoped_session, sessionmaker217- from sqlalchemy.ext.declarative import declarative_base218-219- engine = create_engine('sqlite:////tmp/test.db')220- db_session = scoped_session(sessionmaker(autocommit=False,221- autoflush=False,222- bind=engine)) 223- Base = declarative_base()224- Base.query = db_session.query_property()225-226- def init_db():227- Base.metadata.create_all(bind=engine)228-229-To define your models, just subclass the `Base` class that was created by230-the code above. If you are wondering why we don't have to care about231-threads here (like we did in the SQLite3 example above with the232-:data:`~flask.g` object): that's because SQLAlchemy does that for us233-already with the :class:`~sqlalchemy.orm.scoped_session`.234-235-To use SQLAlchemy in a declarative way with your application, you just236-have to put the following code into your application module. Flask will237-automatically remove database sessions at the end of the request for you::238-239- from yourapplication.database import db_session240-241- @app.after_request242- def shutdown_session(response):243- db_session.remove()244- return response245-246-Here an example model (put that into `models.py` for instance)::247-248- from sqlalchemy import Column, Integer, String249- from yourapplication.database import Base250-251- class User(Base):252- __tablename__ = 'users'253- id = Column(Integer, primary_key=True)254- name = Column(String(50), unique=True)255- email = Column(String(120), unique=True)256-257- def __init__(self, name=None, email=None):258- self.name = name259- self.email = email260-261- def __repr__(self):262- return '<User %r>' % (self.name, self.email)263-264-You can insert entries into the database like this then:265-266->>> from yourapplication.database import db_session267->>> from yourapplication.models import User268->>> u = User('admin', 'admin@localhost')269->>> db_session.add(u)270->>> db_session.commit()271-272-Querying is simple as well:273-274->>> User.query.all()275-[<User u'admin'>]276->>> User.query.filter(User.name == 'admin').first()277-<User u'admin'>278-279-.. _SQLAlchemy: http://www.sqlalchemy.org/280-.. _declarative:281- http://www.sqlalchemy.org/docs/reference/ext/declarative.html282-283-Manual Object Relational Mapping284-````````````````````````````````285-286-*coming soon*287-288-SQL Abstraction Layer289-`````````````````````290-291-*coming soon*292-293-294-.. _template-inheritance:295-296-Template Inheritance297---------------------298-299-The most powerful part of Jinja is template inheritance. Template inheritance300-allows you to build a base "skeleton" template that contains all the common301-elements of your site and defines **blocks** that child templates can override.302-303-Sounds complicated but is very basic. It's easiest to understand it by starting304-with an example.305-306-307-Base Template308-`````````````309-310-This template, which we'll call ``layout.html``, defines a simple HTML skeleton311-document that you might use for a simple two-column page. It's the job of312-"child" templates to fill the empty blocks with content:313-314-.. sourcecode:: html+jinja315-316- <!doctype html>317- <html>318- <head>319- {% block head %}320- <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">321- <title>{% block title %}{% endblock %} - My Webpage</title>322- {% endblock %}323- </head>324- <body>325- <div id="content">{% block content %}{% endblock %}</div>326- <div id="footer">327- {% block footer %}328- © Copyright 2010 by <a href="http://domain.invalid/">you</a>.329- {% endblock %}330- </div>331- </body>332-333-In this example, the ``{% block %}`` tags define four blocks that child templates334-can fill in. All the `block` tag does is to tell the template engine that a335-child template may override those portions of the template.336-337-Child Template338-``````````````339-340-A child template might look like this:341-342-.. sourcecode:: html+jinja343-344- {% extends "layout.html" %}345- {% block title %}Index{% endblock %}346- {% block head %}347- {{ super() }}348- <style type="text/css">349- .important { color: #336699; }350- </style>351- {% endblock %}352- {% block content %}353- <h1>Index</h1>354- <p class="important">355- Welcome on my awesome homepage.356- {% endblock %}357-358-The ``{% extends %}`` tag is the key here. It tells the template engine that359-this template "extends" another template. When the template system evaluates360-this template, first it locates the parent. The extends tag must be the361-first tag in the template. To render the contents of a block defined in362-the parent template, use ``{{ super() }}``.363-364-.. _message-flashing-pattern:365-366-Message Flashing367-----------------368-369-Good applications and user interfaces are all about feedback. If the user370-does not get enough feedback he will probably end up hating the371-application. Flask provides a really simple way to give feedback to a372-user with the flashing system. The flashing system basically makes it373-possible to record a message at the end of a request and access it next374-request and only next request. This is usually combined with a layout375-template that does this.376-377-So here a full example::378-379- from flask import flash, redirect, url_for, render_template380-381- @app.route('/')382- def index():383- return render_template('index.html')384-385- @app.route('/login', methods=['GET', 'POST'])386- def login():387- error = None388- if request.method == 'POST':389- if request.form['username'] != 'admin' or \390- request.form['password'] != 'secret':391- error = 'Invalid credentials'392- else:393- flash('You were sucessfully logged in')394- return redirect(url_for('index'))395- return render_template('login.html', error=error)396-397-And here the ``layout.html`` template which does the magic:398-399-.. sourcecode:: html+jinja400-401- <!doctype html>402- <title>My Application</title>403- {% with messages = get_flashed_messages() %}404- {% if messages %}405- <ul class=flashes>406- {% for message in messages %}407- <li>{{ message }}</li>408- {% endfor %}409- </ul>410- {% endif %}411- {% endwith %}412- {% block body %}{% endblock %}413-414-And here the index.html template:415-416-.. sourcecode:: html+jinja417-418- {% extends "layout.html" %}419- {% block body %}420- <h1>Overview</h1>421- <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>422- {% endblock %}423-424-And of course the login template:425-426-.. sourcecode:: html+jinja427-428- {% extends "layout.html" %}429- {% block body %}430- <h1>Login</h1>431- {% if error %}432- <p class=error><strong>Error:</strong> {{ error }}433- {% endif %}434- <form action="" method=post>435- <dl>436- <dt>Username:437- <dd><input type=text name=username value="{{438- request.form.username }}">439- <dt>Password:440- <dd><input type=password name=password>441- </dl>442- <p><input type=submit value=Login>443- </form>444- {% endblock %}