Skip to content
Myr

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

15 files+601 added−569 removed

modified:docs/_themes/flasky/static/flasky.css_t+104 added-79 removed
13 unmodified lines
14/* -- page layout ----------------------------------------------------------- */15 16body {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}2425div.document {26 background: #fafafa;27}2829div.documentwrapper {30 float: left;31 width: 100%;32}
5 unmodified lines
38hr {39 border: 1px solid #B1B4B6;40}41 38div.document {39 background-color: #eee;40}41 42div.body {43 background-color: #ffffff;44 color: #3E4349;45 padding: 0 30px 30px 30px;46 min-height: 34em;47}4849img.floatingflask {50 padding: 0 0 10px 10px;51 float: right;52}53 54div.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 64div.footer a {55 color: white;65 color: #888;66 text-decoration: underline;67}68 69div.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}7374div.related ul {75 padding: 0 0 0 10px;76}77 78div.related a {68 color: #E9D1C1;79 color: #444;80}81 82div.sphinxsidebar {72 font-size: 0.85em;73 line-height: 1.5em;83 font-size: 14px;84 line-height: 1.5;85}8687div.sphinxsidebarwrapper {77 padding: 20px 0 20px 0;88 padding: 0 20px;89}9091div.sphinxsidebarwrapper p.logo {81 padding: 0 0 10px 0;92 padding: 20px 0 10px 0;93 margin: 0;94 text-align: center;95}96 97div.sphinxsidebar h3,98div.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}106107div.sphinxsidebar h4 {99 font-size: 1.1em;108 font-size: 20px;109}110 111div.sphinxsidebar h3 a {112 color: #444;113}114 106 115div.sphinxsidebar p {116 color: #555;109 padding: 5px 20px;117 margin: 10px 0;118}119 112div.sphinxsidebar p.topless {113}114 120div.sphinxsidebar ul {116 margin: 10px 20px;121 margin: 10px 0;122 padding: 0;123 color: #000;124}125 126div.sphinxsidebar a {127 color: #444;128 text-decoration: none;129}130131div.sphinxsidebar a:hover {132 text-decoration: underline;133}134 135div.sphinxsidebar input {136 border: 1px solid #ccc;137 font-family: 'Georgia', serif;138 font-size: 1em;139}130131div.sphinxsidebar input[type=text]{132 margin-left: 20px;133}140 141/* -- body styles ----------------------------------------------------------- */142 143a {144 color: #004B6B;139 text-decoration: none;145 text-decoration: underline;146}147 148a:hover {149 color: #6D4100;150 text-decoration: underline;151}152153div.body {154 padding-bottom: 40px; /* saved for footer */155}156 157div.body h1,158div.body h2,159div.body h3,160div.body h4,161div.body h5,162div.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 162div.body h1 { border-top: 20px solid white; margin-top: 0; font-size: 200%; }163div.body h2 { font-size: 150%; background-color: #ddd; }164div.body h3 { font-size: 120%; background-color: #eee; }165div.body h4 { font-size: 110%; background-color: #eee; }166div.body h5 { font-size: 100%; background-color: #eee; }167div.body h6 { font-size: 100%; background-color: #eee; }169div.body h1 { margin-top: 0; padding-top: 20px; font-size: 240%; }170div.body h2 { font-size: 180%; }171div.body h3 { font-size: 150%; }172div.body h4 { font-size: 130%; }173div.body h5 { font-size: 100%; }174div.body h6 { font-size: 100%; }175 176a.headerlink {177 color: white;178 padding: 0 4px;
9 unmodified lines
188 line-height: 1.5em;189}190191div.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 191div.admonition p.admonition-title + p {192 display: inline;198199div.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}207208div.admonition p.last {209 margin-bottom: 0;210}211212div.highlight{213 background-color: white;214}215
29 unmodified lines
245 font-size: 0.9em;246}247248img.screenshot {232 -webkit-box-shadow: 4px 4px 3px #cdcdcd;233 -moz-box-shadow: 4px 4px 3px #cdcdcd;249}250251tt.descname, tt.descclassname {252 font-size: 0.95em;238 -webkit-box-shadow: none;239 -moz-box-shadow: none;253}254255tt.descname {256 padding-right: 0.08em;257}258259img.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}264265table.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}271272table.docutils td, table.docutils th {273 border: 1px solid #888;
1 unmodified line
275}276277table.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}283284table.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}289290table.field-list th {291 padding: 0 0.8em 0 0;
5 unmodified lines
297298table.footnote td {299 padding: 0.5em;300}301302dl {303 margin: 0;304 padding: 0;305}306307dl dd {308 margin-left: 30px;309}310 311pre {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}317318dl pre {319 margin-left: -60px;320 padding-left: 60px;321}322323dl dl pre {324 margin-left: -90px;325 padding-left: 90px;326}327 328tt {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}333334tt.xref, a tt {335 background-color: #FBFBFB;
1 unmodified line
337338a:hover tt {339 background: #EEE;340}308309div.document + div.related {310 background: #aaa;311}312313div.document + div.related a {314 color: white;315}
added:docs/tutorial/css.rst+27 added
1Step 7: Adding Style2====================34Now that everything else works, it's time to add some style to the5application. Just create a stylesheet called `style.css` in the `static`6folder we created before:78.. sourcecode:: css910 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
1Step 4: Request Database Connections2------------------------------------34Now we know how we can open database connections and use them for scripts,5but how can we elegantly do that for requests? We will need the database6connection in all our functions so it makes sense to initialize them7before each request and shut them down afterwards.89Flask allows us to do that with the :meth:`~flask.Flask.before_request` and10:meth:`~flask.Flask.after_request` decorators::1112 @app.before_request13 def before_request():14 g.db = connect_db()1516 @app.after_request17 def after_request(response):18 g.db.close()19 return response2021Functions marked with :meth:`~flask.Flask.before_request` are called before22a request and passed no arguments, functions marked with23:meth:`~flask.Flask.after_request` are called after a request and24passed the response that will be sent to the client. They have to return25that response object or a different one. In this case we just return it26unchanged.2728We store our current database connection on the special :data:`~flask.g`29object that flask provides for us. This object stores information for one30request only and is available from within each function. Never store such31things on other objects because this would not work with threaded32environments. That special :data:`~flask.g` object does some magic behind33the scenes to ensure it does the right thing.
added:docs/tutorial/dbinit.rst+57 added
1Step 3: Creating The Database2=============================34Flaskr is a database powered application as outlined earlier, and more5precisely, an application powered by a relational database system. Such6systems need a schema that tells them how to store that information. So7before starting the server for the first time it's important to create8that schema.910Such a schema can be created by piping the `schema.sql` file into the11`sqlite3` command as follows::1213 sqlite3 /tmp/flaskr.db < schema.sql1415The downside of this is that it requires the sqlite3 command to be16installed which is not necessarily the case on every system. Also one has17to provide the path to the database there which leaves some place for18errors. It's a good idea to add a function that initializes the database19for you to the application.2021If you want to do that, you first have to import the22:func:`contextlib.closing` function from the contextlib package. If you23want to use Python 2.5 it's also necessary to enable the `with` statement24first (`__future__` imports must be the very first import)::2526 from __future__ import with_statement27 from contextlib import closing2829Next we can create a function called `init_db` that initializes the30database. For this we can use the `connect_db` function we defined31earlier. 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()3839The :func:`~contextlib.closing` helper function allows us to keep a40connection open for the duration of the `with` block. The41:func:`~flask.Flask.open_resource` method of the application object42supports that functionality out of the box, so it can be used in the43`with` block directly. This function opens a file from the resource44location (your `flaskr` folder) and allows you to read from it. We are45using this here to execute a script on the database connection.4647When 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 to49execute a complete script. Finally we only have to commit the changes.50SQLite 3 and other transactional databases will not commit unless you51explicitly tell it to.5253Now it is possible to create a database by starting up a Python shell and54importing and calling that function::5556>>> from flaskr import init_db57>>> init_db()
added:docs/tutorial/folders.rst+19 added
1Step 0: Creating The Folders2============================34Before we get started, let's create the folders needed for this5application::67 /flaskr8 /static9 /templates1011The `flaskr` folder is not a python package, but just something where we12drop our files. Directly into this folder we will then put our database13schema as well as main module in the following steps. The files inside14the `static` folder are available to users of the application via `HTTP`.15This is the place where css and javascript files go. Inside the16`templates` folder Flask will look for `Jinja2`_ templates. Drop all the17templates there.1819.. _Jinja2: http://jinja.pocoo.org/2/
added:docs/tutorial/index.rst+32 added
1.. _tutorial:23Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn that by example. In this tutorial we will create a8simple microblog application. It only supports one user that can create9text-only entries and there are no feeds or comments, but it still10features everything you need to get started. We will use Flask and SQLite11as database which comes out of the box with Python, so there is nothing12else you need.1314If you want the full sourcecode in advance or for comparison, check out15the `example source`_.1617.. _example source:18 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/1920.. toctree::21 :maxdepth: 22223 introduction24 folders25 schema26 setup27 dbcon28 dbinit29 views30 templates31 css32 testing
added:docs/tutorial/introduction.rst+29 added
1Introducing Flaskr2==================34We will call our blogging application flaskr here, feel free to chose a5less web-2.0-ish name ;) Basically we want it to do the following things:671. let the user sign in and out with credentials specified in the8 configuration. Only one user is supported.92. 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.123. 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.1415We will be using SQlite3 directly for that application because it's good16enough for an application of that size. For larger applications however17it makes a lot of sense to use `SQLAlchemy`_ that handles database18connections in a more intelligent way, allows you to target different19relational databases at once and more. You might also want to consider20one of the popular NoSQL databases if your data is more suited for those.2122Here a screenshot from the final application:2324.. image:: ../_static/flaskr.png25 :align: center26 :class: screenshot27 :alt: screenshot of the final application2829.. _SQLAlchemy: http://www.sqlalchemy.org/
added:docs/tutorial/schema.rst+21 added
1Step 1: Database Schema2=======================34First we want to create the database schema. For this application only a5single table is needed and we only want to support SQLite so that is quite6easy. Just put the following contents into a file named `schema.sql` in7the just created `flaskr` folder:89.. sourcecode:: sql1011 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 );1718This schema consists of a single table called `entries` and each row in19this table has an `id`, a `title` and a `text`. The `id` is an20automatically incrementing integer and a primary key, the other two are21strings that must not be null.
added:docs/tutorial/setup.rst+69 added
1Step 2: Application Setup Code2==============================34Now that we have the schema in place we can create the application module.5Let's call it `flaskr.py` inside the `flaskr` folder. For starters we6will add the imports we will need as well as the config section. For7small applications it's a possibility to drop the configuration directly8into the module which we will be doing here. However a cleaner solution9would be to create a separate `.ini` or `.py` file and load that or import10the values from there.1112::1314 # all the imports15 import sqlite316 from flask import Flask, request, session, g, redirect, url_for, \17 abort, render_template, flash1819 # configuration20 DATABASE = '/tmp/flaskr.db'21 DEBUG = True22 SECRET_KEY = 'development key'23 USERNAME = 'admin'24 PASSWORD = 'default'2526Next we can create our actual application and initialize it with the27config::2829 # create our little application :)30 app = Flask(__name__)31 app.secret_key = SECRET_KEY32 app.debug = DEBUG3334The `secret_key` is needed to keep the client-side sessions secure.35Choose that key wisely and as hard to guess and complex as possible. The36debug flag enables or disables the interactive debugger. Never leave37debug mode activated in a production system because it will allow users to38executed code on the server!3940We also add a method to easily connect to the database specified. That41can be used to open a connection on request and also from the interactive42Python shell or a script. This will come in handy later4344::4546 def connect_db():47 return sqlite3.connect(DATABASE)4849Finally we just add a line to the bottom of the file that fires up the50server if we run that file as standalone application::5152 if __name__ == '__main__':53 app.run()5455With that out of the way you should be able to start up the application56without problems. When you head over to the server you will get an 40457page not found error because we don't have any views yet. But we will58focus on that a little later. First we should get the database working.5960.. admonition:: Troubleshooting6162 If you notice later that the browser cannot connect to the server63 during development, you might want to try this line instead::6465 app.run(host='127.0.0.1')6667 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
1Step 6: The Templates2=====================34Now we should start working on the templates. If we request the URLs now5we would only get an exception that Flask cannot find the templates. The6templates are using `Jinja2`_ syntax and have autoescaping enabled by7default. This means that unless you mark a value in the code with8:class:`~flask.Markup` or with the ``|safe`` filter in the template,9Jinja2 will ensure that special characters such as ``<`` or ``>`` are10escaped with their XML equivalents.1112We are also using template inheritance which makes it possible to reuse13the layout of the website in all pages.1415Put the following templates into the `templates` folder:1617.. _Jinja2: http://jinja.pocoo.org/2/documentation/templates1819layout.html20-----------2122This 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 the24flashed messages if there are any. The ``{% block body %}`` block can be25replaced by a block of the same name (``body``) in a child template.2627The :class:`~flask.session` dict is available in the template as well and28you can use that to check if the user is logged in or not. Note that in29Jinja you can access missing attributes and items of objects / dicts which30makes the following code work, even if there is no ``'logged_in'`` key in31the session:3233.. sourcecode:: html+jinja3435 <!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>5253show_entries.html54-----------------5556This template extends the `layout.html` template from above to display the57messages. Note that the `for` loop iterates over the messages we passed58in with the :func:`~flask.render_template` function. We also tell the59form to submit to your `add_entry` function and use `POST` as `HTTP`60method:6162.. sourcecode:: html+jinja6364 {% 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 %}8586login.html87----------8889Finally the login template which basically just displays a form to allow90the user to login:9192.. sourcecode:: html+jinja9394 {% 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
1Bonus: Testing the Application2===============================34Now that you have finished the application and everything works as5expected, it's probably not the best idea to add automated tests to6simplify modifications in the future. The application above is used as a7basic example of how to perform unittesting in the :ref:`testing` section8of the documentation. Go there to see how easy it is to test Flask9applications.
added:docs/tutorial/views.rst+87 added
1Step 5: The View Functions2==========================34Now that the database connections are working we can start writing the5view functions. We will need four of them:67Show Entries8------------910This view shows all the entries stored in the database. It listens on the11root of the application and will select title and text from the database.12The one with the highest id (the newest entry) on top. The rows returned13from the cursor are tuples with the columns ordered like specified in the14select statement. This is good enough for small applications like here,15but you might want to convert them into a dict. If you are interested how16to do that, check out the :ref:`easy-querying` example.1718The view function will pass the entries as dicts to the19`show_entries.html` template and return the rendered one::2021 @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)2627Add New Entry28-------------2930This view lets the user add new entries if he's logged in. This only31responds 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 and34redirect back to the `show_entries` page::3536 @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'))4546Note that we check that the user is logged in here (the `logged_in` key is47present in the session and `True`).4849Login and Logout50----------------5152These functions are used to sign the user in and out. Login checks the53username and password against the ones from the configuration and sets the54`logged_in` key in the session. If the user logged in successfully that55key is set to `True` and the user is redirected back to the `show_entries`56page. In that case also a message is flashed that informs the user he or57she was logged in successfully. If an error occoured the template is58notified about that and the user asked again::5960 @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)7374The logout function on the other hand removes that key from the session75again. We use a neat trick here: if you use the :meth:`~dict.pop` method76of the dict and pass a second parameter to it (the default) the method77will delete the key from the dictionary if present or do nothing when that78key was not in there. This is helpful because we don't have to check in79that case if the user was logged in.8081::8283 @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 line
2================34.. image:: _static/logo-full.png5 :alt: The Flask Logo with Subtitle6 :align: right6 :class: floatingflask78Welcome to Flask's documentation. This documentation is divided in9different parts. I would suggest to get started with the10:ref:`installation` and then heading over to the :ref:`quickstart`.
26 unmodified lines
3738 foreword39 installation40 quickstart41 tutorial41 tutorial/index42 testing43 patterns44 deploying45 becomingbig
11 unmodified lines
modified:docs/patterns.rst+5 added-4 removed
84 unmodified lines
85 return 'Hello World!'8687.. admonition:: Circular Imports8889 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 lines
deleted:docs/tutorial.rst-484 removed
1.. _tutorial:23Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn that by example. In this tutorial we will create a8simple microblog application. It only supports one user that can create9text-only entries and there are no feeds or comments, but it still10features everything you need to get started. We will use Flask and SQLite11as database which comes out of the box with Python, so there is nothing12else you need.1314If you want the full sourcecode in advance or for comparison, check out15the `example source`_.1617.. _example source:18 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/1920Introducing Flaskr21------------------2223We will call our blogging application flaskr here, feel free to chose a24less web-2.0-ish name ;) Basically we want it to do the following things:25261. let the user sign in and out with credentials specified in the27 configuration. Only one user is supported.282. 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.313. 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.3334We will be using SQlite3 directly for that application because it's good35enough for an application of that size. For larger applications however36it makes a lot of sense to use `SQLAlchemy`_ that handles database37connections in a more intelligent way, allows you to target different38relational databases at once and more. You might also want to consider39one of the popular NoSQL databases if your data is more suited for those.4041Here a screenshot from the final application:4243.. image:: _static/flaskr.png44 :align: center45 :class: screenshot46 :alt: screenshot of the final application4748.. _SQLAlchemy: http://www.sqlalchemy.org/4950Step 0: Creating The Folders51----------------------------5253Before we get started, let's create the folders needed for this54application::5556 /flaskr57 /static58 /templates5960The `flaskr` folder is not a python package, but just something where we61drop our files. Directly into this folder we will then put our database62schema as well as main module in the following steps. The files inside63the `static` folder are available to users of the application via `HTTP`.64This is the place where css and javascript files go. Inside the65`templates` folder Flask will look for `Jinja2`_ templates. Drop all the66templates there.6768.. _Jinja2: http://jinja.pocoo.org/2/6970Step 1: Database Schema71-----------------------7273First we want to create the database schema. For this application only a74single table is needed and we only want to support SQLite so that is quite75easy. Just put the following contents into a file named `schema.sql` in76the just created `flaskr` folder:7778.. sourcecode:: sql7980 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 );8687This schema consists of a single table called `entries` and each row in88this table has an `id`, a `title` and a `text`. The `id` is an89automatically incrementing integer and a primary key, the other two are90strings that must not be null.9192Step 2: Application Setup Code93------------------------------9495Now that we have the schema in place we can create the application module.96Let's call it `flaskr.py` inside the `flaskr` folder. For starters we97will add the imports we will need as well as the config section. For98small applications it's a possibility to drop the configuration directly99into the module which we will be doing here. However a cleaner solution100would be to create a separate `.ini` or `.py` file and load that or import101the values from there.102103::104105 # all the imports106 import sqlite3107 from flask import Flask, request, session, g, redirect, url_for, \108 abort, render_template, flash109110 # configuration111 DATABASE = '/tmp/flaskr.db'112 DEBUG = True113 SECRET_KEY = 'development key'114 USERNAME = 'admin'115 PASSWORD = 'default'116117Next we can create our actual application and initialize it with the118config::119120 # create our little application :)121 app = Flask(__name__)122 app.secret_key = SECRET_KEY123 app.debug = DEBUG124125The `secret_key` is needed to keep the client-side sessions secure.126Choose that key wisely and as hard to guess and complex as possible. The127debug flag enables or disables the interactive debugger. Never leave128debug mode activated in a production system because it will allow users to129executed code on the server!130131We also add a method to easily connect to the database specified. That132can be used to open a connection on request and also from the interactive133Python shell or a script. This will come in handy later134135::136137 def connect_db():138 return sqlite3.connect(DATABASE)139140Finally we just add a line to the bottom of the file that fires up the141server if we run that file as standalone application::142143 if __name__ == '__main__':144 app.run()145146With that out of the way you should be able to start up the application147without problems. When you head over to the server you will get an 404148page not found error because we don't have any views yet. But we will149focus on that a little later. First we should get the database working.150151.. admonition:: Troubleshooting152153 If you notice later that the browser cannot connect to the server154 during development, you might want to try this line instead::155156 app.run(host='127.0.0.1')157158 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.161162Step 3: Creating The Database163-----------------------------164165Flaskr is a database powered application as outlined earlier, and more166precisely, an application powered by a relational database system. Such167systems need a schema that tells them how to store that information. So168before starting the server for the first time it's important to create169that schema.170171Such a schema can be created by piping the `schema.sql` file into the172`sqlite3` command as follows::173174 sqlite3 /tmp/flaskr.db < schema.sql175176The downside of this is that it requires the sqlite3 command to be177installed which is not necessarily the case on every system. Also one has178to provide the path to the database there which leaves some place for179errors. It's a good idea to add a function that initializes the database180for you to the application.181182If you want to do that, you first have to import the183:func:`contextlib.closing` function from the contextlib package. If you184want to use Python 2.5 it's also necessary to enable the `with` statement185first (`__future__` imports must be the very first import)::186187 from __future__ import with_statement188 from contextlib import closing189190Next we can create a function called `init_db` that initializes the191database. For this we can use the `connect_db` function we defined192earlier. 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()199200The :func:`~contextlib.closing` helper function allows us to keep a201connection open for the duration of the `with` block. The202:func:`~flask.Flask.open_resource` method of the application object203supports that functionality out of the box, so it can be used in the204`with` block directly. This function opens a file from the resource205location (your `flaskr` folder) and allows you to read from it. We are206using this here to execute a script on the database connection.207208When 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 to210execute a complete script. Finally we only have to commit the changes.211SQLite 3 and other transactional databases will not commit unless you212explicitly tell it to.213214Now it is possible to create a database by starting up a Python shell and215importing and calling that function::216217>>> from flaskr import init_db218>>> init_db()219220Step 4: Request Database Connections221------------------------------------222223Now we know how we can open database connections and use them for scripts,224but how can we elegantly do that for requests? We will need the database225connection in all our functions so it makes sense to initialize them226before each request and shut them down afterwards.227228Flask allows us to do that with the :meth:`~flask.Flask.before_request` and229:meth:`~flask.Flask.after_request` decorators::230231 @app.before_request232 def before_request():233 g.db = connect_db()234235 @app.after_request236 def after_request(response):237 g.db.close()238 return response239240Functions marked with :meth:`~flask.Flask.before_request` are called before241a request and passed no arguments, functions marked with242:meth:`~flask.Flask.after_request` are called after a request and243passed the response that will be sent to the client. They have to return244that response object or a different one. In this case we just return it245unchanged.246247We store our current database connection on the special :data:`~flask.g`248object that flask provides for us. This object stores information for one249request only and is available from within each function. Never store such250things on other objects because this would not work with threaded251environments. That special :data:`~flask.g` object does some magic behind252the scenes to ensure it does the right thing.253254Step 5: The View Functions255--------------------------256257Now that the database connections are working we can start writing the258view functions. We will need four of them:259260Show Entries261````````````262263This view shows all the entries stored in the database. It listens on the264root of the application and will select title and text from the database.265The one with the highest id (the newest entry) on top. The rows returned266from the cursor are tuples with the columns ordered like specified in the267select statement. This is good enough for small applications like here,268but you might want to convert them into a dict. If you are interested how269to do that, check out the :ref:`easy-querying` example.270271The view function will pass the entries as dicts to the272`show_entries.html` template and return the rendered one::273274 @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)279280Add New Entry281`````````````282283This view lets the user add new entries if he's logged in. This only284responds 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 and287redirect back to the `show_entries` page::288289 @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'))298299Note that we check that the user is logged in here (the `logged_in` key is300present in the session and `True`).301302Login and Logout303````````````````304305These functions are used to sign the user in and out. Login checks the306username and password against the ones from the configuration and sets the307`logged_in` key in the session. If the user logged in successfully that308key is set to `True` and the user is redirected back to the `show_entries`309page. In that case also a message is flashed that informs the user he or310she was logged in successfully. If an error occoured the template is311notified about that and the user asked again::312313 @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)326327The logout function on the other hand removes that key from the session328again. We use a neat trick here: if you use the :meth:`~dict.pop` method329of the dict and pass a second parameter to it (the default) the method330will delete the key from the dictionary if present or do nothing when that331key was not in there. This is helpful because we don't have to check in332that case if the user was logged in.333334::335336 @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'))341342Step 6: The Templates343---------------------344345Now we should start working on the templates. If we request the URLs now346we would only get an exception that Flask cannot find the templates. The347templates are using `Jinja2`_ syntax and have autoescaping enabled by348default. This means that unless you mark a value in the code with349:class:`~flask.Markup` or with the ``|safe`` filter in the template,350Jinja2 will ensure that special characters such as ``<`` or ``>`` are351escaped with their XML equivalents.352353We are also using template inheritance which makes it possible to reuse354the layout of the website in all pages.355356Put the following templates into the `templates` folder:357358layout.html359```````````360361This 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 the363flashed messages if there are any. The ``{% block body %}`` block can be364replaced by a block of the same name (``body``) in a child template.365366The :class:`~flask.session` dict is available in the template as well and367you can use that to check if the user is logged in or not. Note that in368Jinja you can access missing attributes and items of objects / dicts which369makes the following code work, even if there is no ``'logged_in'`` key in370the session:371372.. sourcecode:: html+jinja373374 <!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>391392show_entries.html393`````````````````394395This template extends the `layout.html` template from above to display the396messages. Note that the `for` loop iterates over the messages we passed397in with the :func:`~flask.render_template` function. We also tell the398form to submit to your `add_entry` function and use `POST` as `HTTP`399method:400401.. sourcecode:: html+jinja402403 {% 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 %}424425login.html426``````````427428Finally the login template which basically just displays a form to allow429the user to login:430431.. sourcecode:: html+jinja432433 {% 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 %}447448Step 7: Adding Style449--------------------450451Now that everything else works, it's time to add some style to the452application. Just create a stylesheet called `style.css` in the `static`453folder we created before:454455.. sourcecode:: css456457 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; }475476Bonus: Testing the Application477-------------------------------478479Now that you have finished the application and everything works as480expected, it's probably not the best idea to add automated tests to481simplify modifications in the future. The application above is used as a482basic example of how to perform unittesting in the :ref:`testing` section483of the documentation. Go there to see how easy it is to test Flask484applications.