New style for the documentation. Looks more like the website now.
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 42dd94b · Browse files · 15 files·+601 added−569 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+601 added−569 removed
- other:+601 added−569 removed
Provenance
- Commit
bcf347f- Tree
90baf94- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
42dd94b
15 files changed+601 added−569 removed
modified:docs/_themes/flasky/static/flasky.css_t+104 added-79 removed
13 unmodified lines14 /* -- page layout ----------------------------------------------------------- */15 16 body {17 font-family: 'Georgia', serif;18- font-size: 16px;19- background-color: #555;20- color: #555;18+ font-size: 17px;19+ background-color: #ddd;20+ color: #000;21 margin: 0;22 padding: 0;23 }24 25+div.document {26+ background: #fafafa;27+}28+29 div.documentwrapper {30 float: left;31 width: 100%;32 }5 unmodified lines38 hr {39 border: 1px solid #B1B4B6;40 }41 38-div.document {39- background-color: #eee;40-}41- 42 div.body {43 background-color: #ffffff;44 color: #3E4349;45 padding: 0 30px 30px 30px;46+ min-height: 34em;47 }48+49+img.floatingflask {50+ padding: 0 0 10px 10px;51+ float: right;52+}53 54 div.footer {55+ position: absolute;56+ right: 0;57+ margin-top: -70px;58+ text-align: right;49- color: #ccc;59+ color: #888;60 padding: 10px;51- font-size: 0.8em;61+ font-size: 14px;62 }63 64 div.footer a {55- color: white;65+ color: #888;66 text-decoration: underline;67 }68 69 div.related {60- background-color: #774117;70 line-height: 32px;62- color: #fff;63- text-shadow: 0px 1px 0 #444;64- font-size: 0.9em;71+ color: #888;72 }73+74+div.related ul {75+ padding: 0 0 0 10px;76+}77 78 div.related a {68- color: #E9D1C1;79+ color: #444;80 }81 82 div.sphinxsidebar {72- font-size: 0.85em;73- line-height: 1.5em;83+ font-size: 14px;84+ line-height: 1.5;85 }86 87 div.sphinxsidebarwrapper {77- padding: 20px 0 20px 0;88+ padding: 0 20px;89 }90 91 div.sphinxsidebarwrapper p.logo {81- padding: 0 0 10px 0;92+ padding: 20px 0 10px 0;93 margin: 0;94 text-align: center;95 }96 97 div.sphinxsidebar h3,98 div.sphinxsidebar h4 {99 font-family: 'Garamond', 'Georgia', serif;100 color: #222;90- font-size: 1.2em;101+ font-size: 24px;102 font-weight: normal;92- margin: 0;93- padding: 5px 10px;94- background-color: #ddd;95- text-shadow: 1px 1px 0 white103+ margin: 20px 0 5px 0;104+ padding: 0;105 }106 107 div.sphinxsidebar h4 {99- font-size: 1.1em;108+ font-size: 20px;109 }110 111 div.sphinxsidebar h3 a {112 color: #444;113 }114 106- 115 div.sphinxsidebar p {116 color: #555;109- padding: 5px 20px;117+ margin: 10px 0;118 }119 112-div.sphinxsidebar p.topless {113-}114- 120 div.sphinxsidebar ul {116- margin: 10px 20px;121+ margin: 10px 0;122 padding: 0;123 color: #000;124 }125 126 div.sphinxsidebar a {127 color: #444;128+ text-decoration: none;129 }130+131+div.sphinxsidebar a:hover {132+ text-decoration: underline;133+}134 135 div.sphinxsidebar input {136 border: 1px solid #ccc;137 font-family: 'Georgia', serif;138 font-size: 1em;139 }130-131-div.sphinxsidebar input[type=text]{132- margin-left: 20px;133-}140 141 /* -- body styles ----------------------------------------------------------- */142 143 a {144 color: #004B6B;139- text-decoration: none;145+ text-decoration: underline;146 }147 148 a:hover {149 color: #6D4100;150 text-decoration: underline;151 }152+153+div.body {154+ padding-bottom: 40px; /* saved for footer */155+}156 157 div.body h1,158 div.body h2,159 div.body h3,160 div.body h4,161 div.body h5,162 div.body h6 {163 font-family: 'Garamond', 'Georiga', serif;154- background-color: #bbb;164 font-weight: normal;156- color: #212224;165 margin: 30px 0px 10px 0px;158- padding: 5px 0 5px 10px;159- text-shadow: 0px 1px 0 white;166+ padding: 0;167 }168 162-div.body h1 { border-top: 20px solid white; margin-top: 0; font-size: 200%; }163-div.body h2 { font-size: 150%; background-color: #ddd; }164-div.body h3 { font-size: 120%; background-color: #eee; }165-div.body h4 { font-size: 110%; background-color: #eee; }166-div.body h5 { font-size: 100%; background-color: #eee; }167-div.body h6 { font-size: 100%; background-color: #eee; }169+div.body h1 { margin-top: 0; padding-top: 20px; font-size: 240%; }170+div.body h2 { font-size: 180%; }171+div.body h3 { font-size: 150%; }172+div.body h4 { font-size: 130%; }173+div.body h5 { font-size: 100%; }174+div.body h6 { font-size: 100%; }175 176 a.headerlink {177 color: white;178 padding: 0 4px;9 unmodified lines188 line-height: 1.5em;189 }190 191 div.admonition {185- border: 1px solid #ddd;186- background: white;187- -webkit-box-shadow: 2px 2px 1px #d8d8d8;188- -moz-box-shadow: 2px 2px 1px #d8d8d8;192+ background: #fafafa;193+ margin: 20px -30px;194+ padding: 10px 30px;195+ border-top: 1px solid #ccc;196+ border-bottom: 1px solid #ccc;197 }190- 191-div.admonition p.admonition-title + p {192- display: inline;198+199+div.admonition p.admonition-title {200+ font-family: 'Garamond', 'Georiga', serif;201+ font-weight: normal;202+ font-size: 24px;203+ margin: 0 0 10px 0;204+ padding: 0;205+ line-height: 1;206 }207 208+div.admonition p.last {209+ margin-bottom: 0;210+}211+212 div.highlight{213 background-color: white;214 }215 29 unmodified lines245 font-size: 0.9em;246 }247 248 img.screenshot {232- -webkit-box-shadow: 4px 4px 3px #cdcdcd;233- -moz-box-shadow: 4px 4px 3px #cdcdcd;249 }250 251 tt.descname, tt.descclassname {252 font-size: 0.95em;238- -webkit-box-shadow: none;239- -moz-box-shadow: none;253 }254 255 tt.descname {256 padding-right: 0.08em;257 }258 259+img.screenshot {260+ -moz-box-shadow: 2px 2px 4px #eee;261+ -webkit-box-shadow: 2px 2px 4px #eee;262+ box-shadow: 2px 2px 4px #eee;263+}264+265 table.docutils {266 border: 1px solid #888;248- -webkit-box-shadow: 2px 2px 1px #d8d8d8;249- -moz-box-shadow: 2px 2px 1px #d8d8d8;267+ -moz-box-shadow: 2px 2px 4px #eee;268+ -webkit-box-shadow: 2px 2px 4px #eee;269+ box-shadow: 2px 2px 4px #eee;270 }271 272 table.docutils td, table.docutils th {273 border: 1px solid #888;1 unmodified line275 }276 277 table.field-list, table.footnote {278 border: none;259- -webkit-box-shadow: none;279 -moz-box-shadow: none;280+ -webkit-box-shadow: none;281+ box-shadow: none;282 }283 284 table.footnote {285+ margin: 15px 0;286 width: 100%;287 border: 1px solid #eee;266- -webkit-box-shadow: 1px 1px 1px #d8d8d8;267- -moz-box-shadow: 1px 1px 1px #d8d8d8;288 }289 290 table.field-list th {291 padding: 0 0.8em 0 0;5 unmodified lines297 298 table.footnote td {299 padding: 0.5em;300 }301+302+dl {303+ margin: 0;304+ padding: 0;305+}306+307+dl dd {308+ margin-left: 30px;309+}310 311 pre {283- background: #FDFDFD;284- padding: 10px;285- color: #222;312+ background: #eee;313+ padding: 7px 30px;314+ margin: 15px -30px;315 line-height: 1.3em;287- border: 1px solid #f9f9f9;288- margin: 1.5em 3px 1.5em 0;289- -webkit-box-shadow: 2px 2px 1px #d8d8d8;290- -moz-box-shadow: 2px 2px 1px #d8d8d8;316 }317+318+dl pre {319+ margin-left: -60px;320+ padding-left: 60px;321+}322+323+dl dl pre {324+ margin-left: -90px;325+ padding-left: 90px;326+}327 328 tt {329 background-color: #ecf0f3;330 color: #222;331 /* padding: 1px 2px; */297- -webkit-box-shadow: 1px 1px 1px #d8d8d8;298- -moz-box-shadow: 1px 1px 1px #d8d8d8;332 }333 334 tt.xref, a tt {335 background-color: #FBFBFB;1 unmodified line337 338 a:hover tt {339 background: #EEE;340 }308-309-div.document + div.related {310- background: #aaa;311-}312-313-div.document + div.related a {314- color: white;315-}added:docs/tutorial/css.rst+27 added
1+Step 7: Adding Style2+====================3+4+Now that everything else works, it's time to add some style to the5+application. Just create a stylesheet called `style.css` in the `static`6+folder we created before:7+8+.. sourcecode:: css9+10+ body { font-family: sans-serif; background: #eee; }11+ a, h1, h2 { color: #377BA8; }12+ h1, h2 { font-family: 'Georgia', serif; margin: 0; }13+ h1 { border-bottom: 2px solid #eee; }14+ h2 { font-size: 1.2em; }15+ 16+ .page { margin: 2em auto; width: 35em; border: 5px solid #ccc;17+ padding: 0.8em; background: white; }18+ .entries { list-style: none; margin: 0; padding: 0; }19+ .entries li { margin: 0.8em 1.2em; }20+ .entries li h2 { margin-left: -1em; }21+ .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }22+ .add-entry dl { font-weight: bold; }23+ .metanav { text-align: right; font-size: 0.8em; padding: 0.3em;24+ margin-bottom: 1em; background: #fafafa; }25+ .flash { background: #CEE5F5; padding: 0.5em;26+ border: 1px solid #AACBE2; }27+ .error { background: #F0D6D6; padding: 0.5em; }added:docs/tutorial/dbcon.rst+33 added
1+Step 4: Request Database Connections2+------------------------------------3+4+Now we know how we can open database connections and use them for scripts,5+but how can we elegantly do that for requests? We will need the database6+connection in all our functions so it makes sense to initialize them7+before each request and shut them down afterwards.8+9+Flask allows us to do that with the :meth:`~flask.Flask.before_request` and10+:meth:`~flask.Flask.after_request` decorators::11+12+ @app.before_request13+ def before_request():14+ g.db = connect_db()15+16+ @app.after_request17+ def after_request(response):18+ g.db.close()19+ return response20+21+Functions marked with :meth:`~flask.Flask.before_request` are called before22+a request and passed no arguments, functions marked with23+:meth:`~flask.Flask.after_request` are called after a request and24+passed the response that will be sent to the client. They have to return25+that response object or a different one. In this case we just return it26+unchanged.27+28+We store our current database connection on the special :data:`~flask.g`29+object that flask provides for us. This object stores information for one30+request only and is available from within each function. Never store such31+things on other objects because this would not work with threaded32+environments. That special :data:`~flask.g` object does some magic behind33+the scenes to ensure it does the right thing.added:docs/tutorial/dbinit.rst+57 added
1+Step 3: Creating The Database2+=============================3+4+Flaskr is a database powered application as outlined earlier, and more5+precisely, an application powered by a relational database system. Such6+systems need a schema that tells them how to store that information. So7+before starting the server for the first time it's important to create8+that schema.9+10+Such a schema can be created by piping the `schema.sql` file into the11+`sqlite3` command as follows::12+13+ sqlite3 /tmp/flaskr.db < schema.sql14+15+The downside of this is that it requires the sqlite3 command to be16+installed which is not necessarily the case on every system. Also one has17+to provide the path to the database there which leaves some place for18+errors. It's a good idea to add a function that initializes the database19+for you to the application.20+21+If you want to do that, you first have to import the22+:func:`contextlib.closing` function from the contextlib package. If you23+want to use Python 2.5 it's also necessary to enable the `with` statement24+first (`__future__` imports must be the very first import)::25+26+ from __future__ import with_statement27+ from contextlib import closing28+29+Next we can create a function called `init_db` that initializes the30+database. For this we can use the `connect_db` function we defined31+earlier. Just add that function below the `connect_db` function::32+ 33+ def init_db():34+ with closing(connect_db()) as db:35+ with app.open_resource('schema.sql') as f:36+ db.cursor().executescript(f.read())37+ db.commit()38+39+The :func:`~contextlib.closing` helper function allows us to keep a40+connection open for the duration of the `with` block. The41+:func:`~flask.Flask.open_resource` method of the application object42+supports that functionality out of the box, so it can be used in the43+`with` block directly. This function opens a file from the resource44+location (your `flaskr` folder) and allows you to read from it. We are45+using this here to execute a script on the database connection.46+47+When we connect to a database we get a connection object (here called48+`db`) that can give us a cursor. On that cursor there is a method to49+execute a complete script. Finally we only have to commit the changes.50+SQLite 3 and other transactional databases will not commit unless you51+explicitly tell it to.52+53+Now it is possible to create a database by starting up a Python shell and54+importing and calling that function::55+56+>>> from flaskr import init_db57+>>> init_db()added:docs/tutorial/folders.rst+19 added
1+Step 0: Creating The Folders2+============================3+4+Before we get started, let's create the folders needed for this5+application::6+7+ /flaskr8+ /static9+ /templates10+11+The `flaskr` folder is not a python package, but just something where we12+drop our files. Directly into this folder we will then put our database13+schema as well as main module in the following steps. The files inside14+the `static` folder are available to users of the application via `HTTP`.15+This is the place where css and javascript files go. Inside the16+`templates` folder Flask will look for `Jinja2`_ templates. Drop all the17+templates there.18+19+.. _Jinja2: http://jinja.pocoo.org/2/added:docs/tutorial/index.rst+32 added
1+.. _tutorial:2+3+Tutorial4+========5+6+You want to develop an application with Python and Flask? Here you have7+the chance to learn that by example. In this tutorial we will create a8+simple microblog application. It only supports one user that can create9+text-only entries and there are no feeds or comments, but it still10+features everything you need to get started. We will use Flask and SQLite11+as database which comes out of the box with Python, so there is nothing12+else you need.13+14+If you want the full sourcecode in advance or for comparison, check out15+the `example source`_.16+17+.. _example source:18+ http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/19+20+.. toctree::21+ :maxdepth: 222+23+ introduction24+ folders25+ schema26+ setup27+ dbcon28+ dbinit29+ views30+ templates31+ css32+ testingadded:docs/tutorial/introduction.rst+29 added
1+Introducing Flaskr2+==================3+4+We will call our blogging application flaskr here, feel free to chose a5+less web-2.0-ish name ;) Basically we want it to do the following things:6+7+1. let the user sign in and out with credentials specified in the8+ configuration. Only one user is supported.9+2. when the user is logged in he or she can add new entries to the page10+ consisting of a text-only title and some HTML for the text. This HTML11+ is not sanitized because we trust the user here.12+3. the page shows all entries so far in reverse order (newest on top) and13+ the user can add new ones from there if logged in.14+15+We will be using SQlite3 directly for that application because it's good16+enough for an application of that size. For larger applications however17+it makes a lot of sense to use `SQLAlchemy`_ that handles database18+connections in a more intelligent way, allows you to target different19+relational databases at once and more. You might also want to consider20+one of the popular NoSQL databases if your data is more suited for those.21+22+Here a screenshot from the final application:23+24+.. image:: ../_static/flaskr.png25+ :align: center26+ :class: screenshot27+ :alt: screenshot of the final application28+29+.. _SQLAlchemy: http://www.sqlalchemy.org/added:docs/tutorial/schema.rst+21 added
1+Step 1: Database Schema2+=======================3+4+First we want to create the database schema. For this application only a5+single table is needed and we only want to support SQLite so that is quite6+easy. Just put the following contents into a file named `schema.sql` in7+the just created `flaskr` folder:8+9+.. sourcecode:: sql10+11+ drop table if exists entries;12+ create table entries (13+ id integer primary key autoincrement,14+ title string not null,15+ text string not null16+ );17+18+This schema consists of a single table called `entries` and each row in19+this table has an `id`, a `title` and a `text`. The `id` is an20+automatically incrementing integer and a primary key, the other two are21+strings that must not be null.added:docs/tutorial/setup.rst+69 added
1+Step 2: Application Setup Code2+==============================3+4+Now that we have the schema in place we can create the application module.5+Let's call it `flaskr.py` inside the `flaskr` folder. For starters we6+will add the imports we will need as well as the config section. For7+small applications it's a possibility to drop the configuration directly8+into the module which we will be doing here. However a cleaner solution9+would be to create a separate `.ini` or `.py` file and load that or import10+the values from there.11+12+::13+14+ # all the imports15+ import sqlite316+ from flask import Flask, request, session, g, redirect, url_for, \17+ abort, render_template, flash18+19+ # configuration20+ DATABASE = '/tmp/flaskr.db'21+ DEBUG = True22+ SECRET_KEY = 'development key'23+ USERNAME = 'admin'24+ PASSWORD = 'default'25+26+Next we can create our actual application and initialize it with the27+config::28+29+ # create our little application :)30+ app = Flask(__name__)31+ app.secret_key = SECRET_KEY32+ app.debug = DEBUG33+34+The `secret_key` is needed to keep the client-side sessions secure.35+Choose that key wisely and as hard to guess and complex as possible. The36+debug flag enables or disables the interactive debugger. Never leave37+debug mode activated in a production system because it will allow users to38+executed code on the server!39+40+We also add a method to easily connect to the database specified. That41+can be used to open a connection on request and also from the interactive42+Python shell or a script. This will come in handy later43+44+::45+46+ def connect_db():47+ return sqlite3.connect(DATABASE)48+49+Finally we just add a line to the bottom of the file that fires up the50+server if we run that file as standalone application::51+52+ if __name__ == '__main__':53+ app.run()54+55+With that out of the way you should be able to start up the application56+without problems. When you head over to the server you will get an 40457+page not found error because we don't have any views yet. But we will58+focus on that a little later. First we should get the database working.59+60+.. admonition:: Troubleshooting61+62+ If you notice later that the browser cannot connect to the server63+ during development, you might want to try this line instead::64+65+ app.run(host='127.0.0.1')66+67+ In a nutshell: Werkzeug starts up as IPv6 on many operating systems by68+ default and not every browser is happy with that. This forces IPv469+ usage.added:docs/tutorial/templates.rst+107 added
1+Step 6: The Templates2+=====================3+4+Now we should start working on the templates. If we request the URLs now5+we would only get an exception that Flask cannot find the templates. The6+templates are using `Jinja2`_ syntax and have autoescaping enabled by7+default. This means that unless you mark a value in the code with8+:class:`~flask.Markup` or with the ``|safe`` filter in the template,9+Jinja2 will ensure that special characters such as ``<`` or ``>`` are10+escaped with their XML equivalents.11+12+We are also using template inheritance which makes it possible to reuse13+the layout of the website in all pages.14+15+Put the following templates into the `templates` folder:16+17+.. _Jinja2: http://jinja.pocoo.org/2/documentation/templates18+19+layout.html20+-----------21+22+This template contains the HTML skeleton, the header and a link to log in23+(or log out if the user was already logged in). It also displays the24+flashed messages if there are any. The ``{% block body %}`` block can be25+replaced by a block of the same name (``body``) in a child template.26+27+The :class:`~flask.session` dict is available in the template as well and28+you can use that to check if the user is logged in or not. Note that in29+Jinja you can access missing attributes and items of objects / dicts which30+makes the following code work, even if there is no ``'logged_in'`` key in31+the session:32+33+.. sourcecode:: html+jinja34+35+ <!doctype html>36+ <title>Flaskr</title>37+ <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">38+ <div class=page>39+ <h1>Flaskr</h1>40+ <div class=metanav>41+ {% if not session.logged_in %}42+ <a href="{{ url_for('login') }}">log in</a>43+ {% else %}44+ <a href="{{ url_for('logout') }}">log out</a>45+ {% endif %}46+ </div>47+ {% for message in get_flashed_messages() %}48+ <div class=flash>{{ message }}</div>49+ {% endfor %}50+ {% block body %}{% endblock %}51+ </div>52+53+show_entries.html54+-----------------55+56+This template extends the `layout.html` template from above to display the57+messages. Note that the `for` loop iterates over the messages we passed58+in with the :func:`~flask.render_template` function. We also tell the59+form to submit to your `add_entry` function and use `POST` as `HTTP`60+method:61+62+.. sourcecode:: html+jinja63+64+ {% extends "layout.html" %}65+ {% block body %}66+ {% if session.logged_in %}67+ <form action="{{ url_for('add_entry') }}" method=post class=add-entry>68+ <dl>69+ <dt>Title:70+ <dd><input type=text size=30 name=title>71+ <dt>Text:72+ <dd><textarea name=text rows=5 cols=40></textarea>73+ <dd><input type=submit value=Share>74+ </dl>75+ </form>76+ {% endif %}77+ <ul class=entries>78+ {% for entry in entries %}79+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}80+ {% else %}81+ <li><em>Unbelievable. No entries here so far</em>82+ {% endfor %}83+ </ul>84+ {% endblock %}85+86+login.html87+----------88+89+Finally the login template which basically just displays a form to allow90+the user to login:91+92+.. sourcecode:: html+jinja93+94+ {% extends "layout.html" %}95+ {% block body %}96+ <h2>Login</h2>97+ {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}98+ <form action="{{ url_for('login') }}" method=post>99+ <dl>100+ <dt>Username:101+ <dd><input type=text name=username>102+ <dt>Password:103+ <dd><input type=password name=password>104+ <dd><input type=submit value=Login>105+ </dl>106+ </form>107+ {% endblock %}added:docs/tutorial/testing.rst+9 added
1+Bonus: Testing the Application2+===============================3+4+Now that you have finished the application and everything works as5+expected, it's probably not the best idea to add automated tests to6+simplify modifications in the future. The application above is used as a7+basic example of how to perform unittesting in the :ref:`testing` section8+of the documentation. Go there to see how easy it is to test Flask9+applications.added:docs/tutorial/views.rst+87 added
1+Step 5: The View Functions2+==========================3+4+Now that the database connections are working we can start writing the5+view functions. We will need four of them:6+7+Show Entries8+------------9+10+This view shows all the entries stored in the database. It listens on the11+root of the application and will select title and text from the database.12+The one with the highest id (the newest entry) on top. The rows returned13+from the cursor are tuples with the columns ordered like specified in the14+select statement. This is good enough for small applications like here,15+but you might want to convert them into a dict. If you are interested how16+to do that, check out the :ref:`easy-querying` example.17+18+The view function will pass the entries as dicts to the19+`show_entries.html` template and return the rendered one::20+21+ @app.route('/')22+ def show_entries():23+ cur = g.db.execute('select title, text from entries order by id desc')24+ entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]25+ return render_template('show_entries.html', entries=entries)26+27+Add New Entry28+-------------29+30+This view lets the user add new entries if he's logged in. This only31+responds to `POST` requests, the actual form is shown on the32+`show_entries` page. If everything worked out well we will33+:func:`~flask.flash` an information message to the next request and34+redirect back to the `show_entries` page::35+36+ @app.route('/add', methods=['POST'])37+ def add_entry():38+ if not session.get('logged_in'):39+ abort(401)40+ g.db.execute('insert into entries (title, text) values (?, ?)',41+ [request.form['title'], request.form['text']])42+ g.db.commit()43+ flash('New entry was successfully posted')44+ return redirect(url_for('show_entries'))45+46+Note that we check that the user is logged in here (the `logged_in` key is47+present in the session and `True`).48+49+Login and Logout50+----------------51+52+These functions are used to sign the user in and out. Login checks the53+username and password against the ones from the configuration and sets the54+`logged_in` key in the session. If the user logged in successfully that55+key is set to `True` and the user is redirected back to the `show_entries`56+page. In that case also a message is flashed that informs the user he or57+she was logged in successfully. If an error occoured the template is58+notified about that and the user asked again::59+60+ @app.route('/login', methods=['GET', 'POST'])61+ def login():62+ error = None63+ if request.method == 'POST':64+ if request.form['username'] != USERNAME:65+ error = 'Invalid username'66+ elif request.form['password'] != PASSWORD:67+ error = 'Invalid password'68+ else:69+ session['logged_in'] = True70+ flash('You were logged in')71+ return redirect(url_for('show_entries'))72+ return render_template('login.html', error=error)73+74+The logout function on the other hand removes that key from the session75+again. We use a neat trick here: if you use the :meth:`~dict.pop` method76+of the dict and pass a second parameter to it (the default) the method77+will delete the key from the dictionary if present or do nothing when that78+key was not in there. This is helpful because we don't have to check in79+that case if the user was logged in.80+81+::82+83+ @app.route('/logout')84+ def logout():85+ session.pop('logged_in', None)86+ flash('You were logged out')87+ return redirect(url_for('show_entries'))modified:docs/index.rst+2 added-2 removed
1 unmodified line2 ================3 4 .. image:: _static/logo-full.png5 :alt: The Flask Logo with Subtitle6- :align: right6+ :class: floatingflask7 8 Welcome to Flask's documentation. This documentation is divided in9 different parts. I would suggest to get started with the10 :ref:`installation` and then heading over to the :ref:`quickstart`.26 unmodified lines37 38 foreword39 installation40 quickstart41- tutorial41+ tutorial/index42 testing43 patterns44 deploying45 becomingbig11 unmodified linesmodified:docs/patterns.rst+5 added-4 removed
84 unmodified lines85 return 'Hello World!'86 87 .. admonition:: Circular Imports88 89- Every Python programmer hates it, and yet we just did that: circular90- imports (That's when two module depend on each one. In this case91- `views.py` depends on `__init__.py`). Be advised that this is a bad92- idea in general but here it is actually fine. The reason for this is89+ 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 347 unmodified linesdeleted:docs/tutorial.rst-484 removed
1-.. _tutorial:2-3-Tutorial4-========5-6-You want to develop an application with Python and Flask? Here you have7-the chance to learn that by example. In this tutorial we will create a8-simple microblog application. It only supports one user that can create9-text-only entries and there are no feeds or comments, but it still10-features everything you need to get started. We will use Flask and SQLite11-as database which comes out of the box with Python, so there is nothing12-else you need.13-14-If you want the full sourcecode in advance or for comparison, check out15-the `example source`_.16-17-.. _example source:18- http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/19-20-Introducing Flaskr21-------------------22-23-We will call our blogging application flaskr here, feel free to chose a24-less web-2.0-ish name ;) Basically we want it to do the following things:25-26-1. let the user sign in and out with credentials specified in the27- configuration. Only one user is supported.28-2. when the user is logged in he or she can add new entries to the page29- consisting of a text-only title and some HTML for the text. This HTML30- is not sanitized because we trust the user here.31-3. the page shows all entries so far in reverse order (newest on top) and32- the user can add new ones from there if logged in.33-34-We will be using SQlite3 directly for that application because it's good35-enough for an application of that size. For larger applications however36-it makes a lot of sense to use `SQLAlchemy`_ that handles database37-connections in a more intelligent way, allows you to target different38-relational databases at once and more. You might also want to consider39-one of the popular NoSQL databases if your data is more suited for those.40-41-Here a screenshot from the final application:42-43-.. image:: _static/flaskr.png44- :align: center45- :class: screenshot46- :alt: screenshot of the final application47-48-.. _SQLAlchemy: http://www.sqlalchemy.org/49-50-Step 0: Creating The Folders51-----------------------------52-53-Before we get started, let's create the folders needed for this54-application::55-56- /flaskr57- /static58- /templates59-60-The `flaskr` folder is not a python package, but just something where we61-drop our files. Directly into this folder we will then put our database62-schema as well as main module in the following steps. The files inside63-the `static` folder are available to users of the application via `HTTP`.64-This is the place where css and javascript files go. Inside the65-`templates` folder Flask will look for `Jinja2`_ templates. Drop all the66-templates there.67-68-.. _Jinja2: http://jinja.pocoo.org/2/69-70-Step 1: Database Schema71------------------------72-73-First we want to create the database schema. For this application only a74-single table is needed and we only want to support SQLite so that is quite75-easy. Just put the following contents into a file named `schema.sql` in76-the just created `flaskr` folder:77-78-.. sourcecode:: sql79-80- drop table if exists entries;81- create table entries (82- id integer primary key autoincrement,83- title string not null,84- text string not null85- );86-87-This schema consists of a single table called `entries` and each row in88-this table has an `id`, a `title` and a `text`. The `id` is an89-automatically incrementing integer and a primary key, the other two are90-strings that must not be null.91-92-Step 2: Application Setup Code93-------------------------------94-95-Now that we have the schema in place we can create the application module.96-Let's call it `flaskr.py` inside the `flaskr` folder. For starters we97-will add the imports we will need as well as the config section. For98-small applications it's a possibility to drop the configuration directly99-into the module which we will be doing here. However a cleaner solution100-would be to create a separate `.ini` or `.py` file and load that or import101-the values from there.102-103-::104-105- # all the imports106- import sqlite3107- from flask import Flask, request, session, g, redirect, url_for, \108- abort, render_template, flash109-110- # configuration111- DATABASE = '/tmp/flaskr.db'112- DEBUG = True113- SECRET_KEY = 'development key'114- USERNAME = 'admin'115- PASSWORD = 'default'116-117-Next we can create our actual application and initialize it with the118-config::119-120- # create our little application :)121- app = Flask(__name__)122- app.secret_key = SECRET_KEY123- app.debug = DEBUG124-125-The `secret_key` is needed to keep the client-side sessions secure.126-Choose that key wisely and as hard to guess and complex as possible. The127-debug flag enables or disables the interactive debugger. Never leave128-debug mode activated in a production system because it will allow users to129-executed code on the server!130-131-We also add a method to easily connect to the database specified. That132-can be used to open a connection on request and also from the interactive133-Python shell or a script. This will come in handy later134-135-::136-137- def connect_db():138- return sqlite3.connect(DATABASE)139-140-Finally we just add a line to the bottom of the file that fires up the141-server if we run that file as standalone application::142-143- if __name__ == '__main__':144- app.run()145-146-With that out of the way you should be able to start up the application147-without problems. When you head over to the server you will get an 404148-page not found error because we don't have any views yet. But we will149-focus on that a little later. First we should get the database working.150-151-.. admonition:: Troubleshooting152-153- If you notice later that the browser cannot connect to the server154- during development, you might want to try this line instead::155-156- app.run(host='127.0.0.1')157-158- In a nutshell: Werkzeug starts up as IPv6 on many operating systems by159- default and not every browser is happy with that. This forces IPv4160- usage.161-162-Step 3: Creating The Database163------------------------------164-165-Flaskr is a database powered application as outlined earlier, and more166-precisely, an application powered by a relational database system. Such167-systems need a schema that tells them how to store that information. So168-before starting the server for the first time it's important to create169-that schema.170-171-Such a schema can be created by piping the `schema.sql` file into the172-`sqlite3` command as follows::173-174- sqlite3 /tmp/flaskr.db < schema.sql175-176-The downside of this is that it requires the sqlite3 command to be177-installed which is not necessarily the case on every system. Also one has178-to provide the path to the database there which leaves some place for179-errors. It's a good idea to add a function that initializes the database180-for you to the application.181-182-If you want to do that, you first have to import the183-:func:`contextlib.closing` function from the contextlib package. If you184-want to use Python 2.5 it's also necessary to enable the `with` statement185-first (`__future__` imports must be the very first import)::186-187- from __future__ import with_statement188- from contextlib import closing189-190-Next we can create a function called `init_db` that initializes the191-database. For this we can use the `connect_db` function we defined192-earlier. Just add that function below the `connect_db` function::193- 194- def init_db():195- with closing(connect_db()) as db:196- with app.open_resource('schema.sql') as f:197- db.cursor().executescript(f.read())198- db.commit()199-200-The :func:`~contextlib.closing` helper function allows us to keep a201-connection open for the duration of the `with` block. The202-:func:`~flask.Flask.open_resource` method of the application object203-supports that functionality out of the box, so it can be used in the204-`with` block directly. This function opens a file from the resource205-location (your `flaskr` folder) and allows you to read from it. We are206-using this here to execute a script on the database connection.207-208-When we connect to a database we get a connection object (here called209-`db`) that can give us a cursor. On that cursor there is a method to210-execute a complete script. Finally we only have to commit the changes.211-SQLite 3 and other transactional databases will not commit unless you212-explicitly tell it to.213-214-Now it is possible to create a database by starting up a Python shell and215-importing and calling that function::216-217->>> from flaskr import init_db218->>> init_db()219-220-Step 4: Request Database Connections221-------------------------------------222-223-Now we know how we can open database connections and use them for scripts,224-but how can we elegantly do that for requests? We will need the database225-connection in all our functions so it makes sense to initialize them226-before each request and shut them down afterwards.227-228-Flask allows us to do that with the :meth:`~flask.Flask.before_request` and229-:meth:`~flask.Flask.after_request` decorators::230-231- @app.before_request232- def before_request():233- g.db = connect_db()234-235- @app.after_request236- def after_request(response):237- g.db.close()238- return response239-240-Functions marked with :meth:`~flask.Flask.before_request` are called before241-a request and passed no arguments, functions marked with242-:meth:`~flask.Flask.after_request` are called after a request and243-passed the response that will be sent to the client. They have to return244-that response object or a different one. In this case we just return it245-unchanged.246-247-We store our current database connection on the special :data:`~flask.g`248-object that flask provides for us. This object stores information for one249-request only and is available from within each function. Never store such250-things on other objects because this would not work with threaded251-environments. That special :data:`~flask.g` object does some magic behind252-the scenes to ensure it does the right thing.253-254-Step 5: The View Functions255---------------------------256-257-Now that the database connections are working we can start writing the258-view functions. We will need four of them:259-260-Show Entries261-````````````262-263-This view shows all the entries stored in the database. It listens on the264-root of the application and will select title and text from the database.265-The one with the highest id (the newest entry) on top. The rows returned266-from the cursor are tuples with the columns ordered like specified in the267-select statement. This is good enough for small applications like here,268-but you might want to convert them into a dict. If you are interested how269-to do that, check out the :ref:`easy-querying` example.270-271-The view function will pass the entries as dicts to the272-`show_entries.html` template and return the rendered one::273-274- @app.route('/')275- def show_entries():276- cur = g.db.execute('select title, text from entries order by id desc')277- entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]278- return render_template('show_entries.html', entries=entries)279-280-Add New Entry281-`````````````282-283-This view lets the user add new entries if he's logged in. This only284-responds to `POST` requests, the actual form is shown on the285-`show_entries` page. If everything worked out well we will286-:func:`~flask.flash` an information message to the next request and287-redirect back to the `show_entries` page::288-289- @app.route('/add', methods=['POST'])290- def add_entry():291- if not session.get('logged_in'):292- abort(401)293- g.db.execute('insert into entries (title, text) values (?, ?)',294- [request.form['title'], request.form['text']])295- g.db.commit()296- flash('New entry was successfully posted')297- return redirect(url_for('show_entries'))298-299-Note that we check that the user is logged in here (the `logged_in` key is300-present in the session and `True`).301-302-Login and Logout303-````````````````304-305-These functions are used to sign the user in and out. Login checks the306-username and password against the ones from the configuration and sets the307-`logged_in` key in the session. If the user logged in successfully that308-key is set to `True` and the user is redirected back to the `show_entries`309-page. In that case also a message is flashed that informs the user he or310-she was logged in successfully. If an error occoured the template is311-notified about that and the user asked again::312-313- @app.route('/login', methods=['GET', 'POST'])314- def login():315- error = None316- if request.method == 'POST':317- if request.form['username'] != USERNAME:318- error = 'Invalid username'319- elif request.form['password'] != PASSWORD:320- error = 'Invalid password'321- else:322- session['logged_in'] = True323- flash('You were logged in')324- return redirect(url_for('show_entries'))325- return render_template('login.html', error=error)326-327-The logout function on the other hand removes that key from the session328-again. We use a neat trick here: if you use the :meth:`~dict.pop` method329-of the dict and pass a second parameter to it (the default) the method330-will delete the key from the dictionary if present or do nothing when that331-key was not in there. This is helpful because we don't have to check in332-that case if the user was logged in.333-334-::335-336- @app.route('/logout')337- def logout():338- session.pop('logged_in', None)339- flash('You were logged out')340- return redirect(url_for('show_entries'))341-342-Step 6: The Templates343----------------------344-345-Now we should start working on the templates. If we request the URLs now346-we would only get an exception that Flask cannot find the templates. The347-templates are using `Jinja2`_ syntax and have autoescaping enabled by348-default. This means that unless you mark a value in the code with349-:class:`~flask.Markup` or with the ``|safe`` filter in the template,350-Jinja2 will ensure that special characters such as ``<`` or ``>`` are351-escaped with their XML equivalents.352-353-We are also using template inheritance which makes it possible to reuse354-the layout of the website in all pages.355-356-Put the following templates into the `templates` folder:357-358-layout.html359-```````````360-361-This template contains the HTML skeleton, the header and a link to log in362-(or log out if the user was already logged in). It also displays the363-flashed messages if there are any. The ``{% block body %}`` block can be364-replaced by a block of the same name (``body``) in a child template.365-366-The :class:`~flask.session` dict is available in the template as well and367-you can use that to check if the user is logged in or not. Note that in368-Jinja you can access missing attributes and items of objects / dicts which369-makes the following code work, even if there is no ``'logged_in'`` key in370-the session:371-372-.. sourcecode:: html+jinja373-374- <!doctype html>375- <title>Flaskr</title>376- <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">377- <div class=page>378- <h1>Flaskr</h1>379- <div class=metanav>380- {% if not session.logged_in %}381- <a href="{{ url_for('login') }}">log in</a>382- {% else %}383- <a href="{{ url_for('logout') }}">log out</a>384- {% endif %}385- </div>386- {% for message in get_flashed_messages() %}387- <div class=flash>{{ message }}</div>388- {% endfor %}389- {% block body %}{% endblock %}390- </div>391-392-show_entries.html393-`````````````````394-395-This template extends the `layout.html` template from above to display the396-messages. Note that the `for` loop iterates over the messages we passed397-in with the :func:`~flask.render_template` function. We also tell the398-form to submit to your `add_entry` function and use `POST` as `HTTP`399-method:400-401-.. sourcecode:: html+jinja402-403- {% extends "layout.html" %}404- {% block body %}405- {% if session.logged_in %}406- <form action="{{ url_for('add_entry') }}" method=post class=add-entry>407- <dl>408- <dt>Title:409- <dd><input type=text size=30 name=title>410- <dt>Text:411- <dd><textarea name=text rows=5 cols=40></textarea>412- <dd><input type=submit value=Share>413- </dl>414- </form>415- {% endif %}416- <ul class=entries>417- {% for entry in entries %}418- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}419- {% else %}420- <li><em>Unbelievable. No entries here so far</em>421- {% endfor %}422- </ul>423- {% endblock %}424-425-login.html426-``````````427-428-Finally the login template which basically just displays a form to allow429-the user to login:430-431-.. sourcecode:: html+jinja432-433- {% extends "layout.html" %}434- {% block body %}435- <h2>Login</h2>436- {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}437- <form action="{{ url_for('login') }}" method=post>438- <dl>439- <dt>Username:440- <dd><input type=text name=username>441- <dt>Password:442- <dd><input type=password name=password>443- <dd><input type=submit value=Login>444- </dl>445- </form>446- {% endblock %}447-448-Step 7: Adding Style449---------------------450-451-Now that everything else works, it's time to add some style to the452-application. Just create a stylesheet called `style.css` in the `static`453-folder we created before:454-455-.. sourcecode:: css456-457- body { font-family: sans-serif; background: #eee; }458- a, h1, h2 { color: #377BA8; }459- h1, h2 { font-family: 'Georgia', serif; margin: 0; }460- h1 { border-bottom: 2px solid #eee; }461- h2 { font-size: 1.2em; }462- 463- .page { margin: 2em auto; width: 35em; border: 5px solid #ccc;464- padding: 0.8em; background: white; }465- .entries { list-style: none; margin: 0; padding: 0; }466- .entries li { margin: 0.8em 1.2em; }467- .entries li h2 { margin-left: -1em; }468- .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }469- .add-entry dl { font-weight: bold; }470- .metanav { text-align: right; font-size: 0.8em; padding: 0.3em;471- margin-bottom: 1em; background: #fafafa; }472- .flash { background: #CEE5F5; padding: 0.5em;473- border: 1px solid #AACBE2; }474- .error { background: #F0D6D6; padding: 0.5em; }475-476-Bonus: Testing the Application477--------------------------------478-479-Now that you have finished the application and everything works as480-expected, it's probably not the best idea to add automated tests to481-simplify modifications in the future. The application above is used as a482-basic example of how to perform unittesting in the :ref:`testing` section483-of the documentation. Go there to see how easy it is to test Flask484-applications.