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
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.