tutorial.rst
This file
Path
docs/tutorial.rst
484 lines · 18.0 KiB
Last changed by
request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
History of this fileTake it
First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 1–33why, one step back1.. _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.33Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 34–40why, one step back34We 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.40First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 41–47why, one step back41Here a screenshot from the final application:4243.. image:: _static/flaskr.png44 :align: center45 :class: screenshot46 :alt: screenshot of the final application47Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 48–49why, one step back48.. _SQLAlchemy: http://www.sqlalchemy.org/49First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 50–61why, one step back50Step 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 databaseBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 62–66why, one step back62schema 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.First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 67why, one step back67Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 68–69why, one step back68.. _Jinja2: http://jinja.pocoo.org/2/69First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 70–96why, one step back70Step 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 weBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 97–101why, one step back97will 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.First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 102why, one step back102Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 103–104why, one step back103::104First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 105–106why, one step back105 # all the imports106 import sqlite3Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 107–108why, one step back107 from flask import Flask, request, session, g, redirect, url_for, \108 abort, render_template, flashFirst part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 109–116why, one step back109110 # configuration111 DATABASE = '/tmp/flaskr.db'112 DEBUG = True113 SECRET_KEY = 'development key'114 USERNAME = 'admin'115 PASSWORD = 'default'116Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 117–118why, one step back117Next we can create our actual application and initialize it with the118config::First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 119–124why, one step back119120 # create our little application :)121 app = Flask(__name__)122 app.secret_key = SECRET_KEY123 app.debug = DEBUG124Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 125–129why, one step back125The `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!First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 130why, one step back130Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 131–136why, one step back131We 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::136First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 137–145why, one step back137 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()145Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 146–150why, one step back146With 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.150First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 151–190why, one step back151.. 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 theBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 191–192why, one step back191database. For this we can use the `connect_db` function we defined192earlier. Just add that function below the `connect_db` function::First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 193–199why, one step back193 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()199Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 200–213why, one step back200The :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.213First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 214–227why, one step back214Now 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.227request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
lines 228–229why, one step back228Flask allows us to do that with the :meth:`~flask.Flask.before_request` and229:meth:`~flask.Flask.after_request` decorators::First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 230why, one step back230request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 231why, one step back231 @app.before_requestFirst part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 232–234why, one step back232 def before_request():233 g.db = connect_db()234request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 235why, one step back235 @app.after_requestFirst part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 236–239why, one step back236 def after_request(response):237 g.db.close()238 return response239request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 240why, one step back240Functions marked with :meth:`~flask.Flask.before_request` are called beforeFirst part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 241why, one step back241a request and passed no arguments, functions marked withrequest_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 242why, one step back242:meth:`~flask.Flask.after_request` are called after a request andFirst part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 243–257why, one step back243passed 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 therequest_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 258why, one step back258view functions. We will need four of them:First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 259–262why, one step back259260Show Entries261````````````262Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 263–269why, one step back263This 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.First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 270why, one step back270Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 271–273why, one step back271The view function will pass the entries as dicts to the272`show_entries.html` template and return the rendered one::273First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 274–284why, one step back274 @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 theBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 285–287why, one step back285`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::First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 288–298why, one step back288289 @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'))298Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 299–301why, one step back299Note that we check that the user is logged in here (the `logged_in` key is300present in the session and `True`).301First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 302–304why, one step back302Login and Logout303````````````````304Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 305–311why, one step back305These 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::First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 312–326why, one step back312313 @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)326Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 327–335why, one step back327The 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::335First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 336–345why, one step back336 @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 nowBeefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 346–351why, one step back346we 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.First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
line 352why, one step back352Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 353–355why, one step back353We are also using template inheritance which makes it possible to reuse354the layout of the website in all pages.355First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 356–360why, one step back356Put the following templates into the `templates` folder:357358layout.html359```````````360Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 361–371why, one step back361This 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:371First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 372–394why, one step back372.. 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`````````````````394Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 395–400why, one step back395This 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:400First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 401–404why, one step back401.. sourcecode:: html+jinja402403 {% extends "layout.html" %}404 {% block body %}Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
line 405why, one step back405 {% if session.logged_in %}First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 406–427why, one step back406 <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``````````427Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 428–430why, one step back428Finally the login template which basically just displays a form to allow429the user to login:430First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40
lines 431–446why, one step back431.. 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 %}Beefed up the tutorialArmin Ronacherbefore adoption6dd92ae
lines 447–484why, one step back447448Step 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.