Skip to content
Myr

Beefed up the tutorial

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 1246f40 · Browse files · 7 files+306 added−92 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+306 added−92 removed

  • other:+306 added−92 removed

7 files+306 added−92 removed

modified:docs/patterns.rst+2 added
38 unmodified lines
39 def after_request(response):40 g.db.close()41 return response4243.. _easy-querying:4445Easy Querying46`````````````4748Now in each request handling function you can access `g.db` to get the
204 unmodified lines
modified:docs/quickstart.rst+8 added
87 unmodified lines
88 app.run(debug=True)8990Both will have exactly the same effect.9192.. admonition:: Attention9394 The interactive debugger however does not work in forking environments95 which makes it nearly impossible to use on production servers but the96 debugger still allows the execution of arbitrary code which makes it a97 major security risk and **must never be used on production machines**98 because of that.99100101Routing102-------103104As you have seen above, the :meth:`~flask.Flask.route` decorator is used
520 unmodified lines
modified:docs/testing.rst+114 added-43 removed
20 unmodified lines
2122The Application23---------------2425First we need an application to test for functionality. Let's start26simple with a Hello World application (`hello.py`)::25First we need an application to test for functionality. For the testing26we will use the application from the :ref:`tutorial`. If you don't have27that application yet, get the sources from `the examples`_.2828 from flask import Flask, render_template_string29 app = Flask(__name__)29.. _the examples:30 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/3131 @app.route('/')32 @app.route('/<name>')33 def hello(name='World'):34 return render_template_string('''35 <!doctype html>36 <title>Hello {{ name }}!</title>37 <h1>Hello {{ name }}!</h1>38 ''', name=name)3932The Testing Skeleton33--------------------3435In order to test that, we add a second module (44`hello_tests.py`) and create a unittest skeleton there::36`flaskr_tests.py`) and create a unittest skeleton there::3738 import unittest47 import hello39 import flaskr40 import tempfile4149 class HelloWorldTestCase(unittest.TestCase):42 class FlaskrTestCase(unittest.TestCase):4344 def setUp(self):45 self.db = tempfile.NamedTemporaryFile()52 self.app = hello.app.test_client()46 self.app = flaskr.app.test_client()47 flaskr.DATABASE = self.db.name48 flaskr.init_db()4950 if __name__ == '__main__':51 unittest.main()5257The code in the `setUp` function creates a new test client. That function58is called before each individual test function. What the test client does59for us is giving us a simple interface to the application. We can trigger60test requests to the application and the client will also keep track of61cookies for us.53The code in the `setUp` function creates a new test client and initialize54a new database. That function is called before each individual test function.55What the test client does for us is giving us a simple interface to the56application. We can trigger test requests to the application and the57client will also keep track of cookies for us.5859Because SQLite3 is filesystem based we can easily use the tempfile module60to create a temporary database and initialize it. Just make sure that you61keep a reference to the :class:`~tempfile.NamedTemporaryFile` around (we62store it as `self.db` because of that) so that the garbage collector does63not remove that object and with it the database from the filesystem.6465If we now run that testsuite, we should see the following output::6665 $ python hello_tests.py67 $ python flaskr_tests.py6869 ----------------------------------------------------------------------70 Ran 0 tests in 0.000s71 72 OK7372Even though it did not run any tests, we already know that our hello74Even though it did not run any tests, we already know that our flaskr75application is syntactically valid, otherwise the import would have died76with an exception.7778The First Test79--------------8079Now we can add the first test. Let's check that the application greets us80with "Hello World" if we access it on ``/``. For that we modify our81created test case class so that it looks like this::81Now we can add the first test. Let's check that the application shows82"No entries here so far" if we access the root of the application (``/``).83For that we modify our created test case class so that it looks like84this::8583 class HelloWorldTestCase(unittest.TestCase):86 class FlaskrTestCase(unittest.TestCase):8788 def setUp(self):89 self.db = tempfile.NamedTemporaryFile()86 self.app = hello.app.test_client()90 self.app = flaskr.app.test_client()91 flaskr.DATABASE = self.db.name92 flaskr.init_db()9388 def test_hello_world(self):94 def test_empty_db(self):95 rv = self.app.get('/')90 assert 'Hello World!' in rv.data96 assert 'No entries here so far' in rv.data9798Test functions begin with the word `test`. Every function named like that99will be picked up automatically. By using `self.app.get` we can send an100HTTP `GET` request to the application with the given path. The return101value will be a :class:`~flask.Flask.response_class` object. We can now102use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the103return value (as string) from the application. In this case, we ensure98that ``'Hello World!'`` is part of the output.104that ``'No entries here so far'`` is part of the output.105100Run it again and you should see one passing test. Let's add a second test101here::106Run it again and you should see one passing test::107103 def test_hello_name(self):104 rv = self.app.get('/Peter')105 assert 'Hello Peter!' in rv.data108 $ python flaskr_tests.py109 .110 ----------------------------------------------------------------------111 Ran 1 test in 0.034s112107Of course you can submit forms with the test client as well. For that and108other features of the test client, check the documentation of the Werkzeug109test :class:`~werkzeug.Client` and the tests of the MiniTwit example110application:113 OK114112- Werkzeug Test :class:`~werkzeug.Client`113- `MiniTwit Example`_115Of course you can submit forms with the test client as well which we will116use now to log our user in.117118Logging In and Out119------------------120121The majority of the functionality of our application is only available for122the administration user. So we need a way to log our test client into the123application and out of it again. For that we fire some requests to the124login and logout pages with the required form data (username and125password). Because the login and logout pages redirect, we tell the126client to `follow_redirects`.127128Add the following two methods do your `FlaskrTestCase` class::129130 def login(self, username, password):131 return self.app.post('/login', data=dict(132 username=username,133 password=password134 ), follow_redirects=True)135136 def logout(self):137 return self.app.get('/logout', follow_redirects=True)138139Now we can easily test if logging in and out works and that it fails with140invalid credentials. Add this as new test to the class::141142 def test_login_logout(self):143 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)144 assert 'You were logged in' in rv.data145 rv = self.logout()146 assert 'You were logged out' in rv.data147 rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)148 assert 'Invalid username' in rv.data149 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')150 assert 'Invalid password' in rv.data151152Test Adding Messages153--------------------154155Now we can also test that adding messages works. Add a new test method156like this::157158 def test_messages(self):159 self.login(flaskr.USERNAME, flaskr.PASSWORD)160 rv = self.app.post('/add', data=dict(161 title='<Hello>',162 text='<strong>HTML</strong> allowed here'163 ), follow_redirects=True)164 assert 'No entries here so far' not in rv.data165 self.login(flaskr.USERNAME, flaskr.PASSWORD)166 assert '&lt;Hello&gt' in rv.data167 assert '<strong>HTML</strong> allowed here' in rv.data168169Here we also check that HTML is allowed in the text but not in the title170which is the intended behavior.171172Running that should now give us three passing tests::173174 $ python flaskr_tests.py 175 ...176 ----------------------------------------------------------------------177 Ran 3 tests in 0.332s178 179 OK180181For more complex tests with headers and status codes, check out the182`MiniTwit Example`_ from the sources. That one contains a larger test183suite.184185186.. _MiniTwit Example:187 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/
modified:docs/tutorial.rst+159 added-29 removed
29 unmodified lines
30 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 this
4 unmodified lines
58 /templates5960The `flaskr` folder is not a python package, but just something where we61drop our files. Directly into this folder we will then put our database53schema as well as main module in the following steps.62schema 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 a
19 unmodified lines
93------------------------------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 we82will add the imports we will need as well as the config section::97will 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 sqlite386 from flask import Flask, request, session, g, redirect, url_for, abort, \87 render_template, flash107 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'11696The `with_statement` and :func:`~contextlib.closing` function are used to97make dealing with the database connection easier later on for setting up98the initial database. Next we can create our actual application and99initialize it with the config::117Next 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 = DEBUG124106We can also add a method to easily connect to the database sepcified::125The `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 the
1 unmodified line
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::
3 unmodified lines
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.161128With that out of the way you should be able to start up the application129without problems. When you head over to the server you will get an 404130page not found error because we don't have any views yet. But we will131focus on that a little later. First we should get the database working.132162Step 3: Creating The Database163-----------------------------164165Flaskr is a database powered application as outlined earlier, and more
21 unmodified lines
187 from __future__ import with_statement188 from contextlib import closing189190Next we can create a function called `init_db` that initializes the162database::191database. 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()219176The :meth:`~flask.Flask.open_resource` function opens a file from the177resource location (your flaskr folder) and allows you to read from it. We178are using this here to execute a script on the database connection.179180When we connect to a database we get a connection object (here called181`db`) that can give us a cursor. On that cursor there is a method to182execute a complete script. Finally we only have to commit the changes and183close the transaction.184220Step 4: Request Database Connections221------------------------------------222223Now we know how we can open database connections and use them for scripts,
35 unmodified lines
259260Show Entries261````````````262228This view shows all the entries stored in the database::263This 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()]
3 unmodified lines
281`````````````282283This view lets the user add new entries if he's logged in. This only284responds to `POST` requests, the actual form is shown on the241`show_entries` page::285`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'):
3 unmodified lines
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````````````````304256These functions are used to sign the user in and out::305These 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 = None
7 unmodified lines
323 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')
2 unmodified lines
342Step 6: The Templates343---------------------344345Now we should start working on the templates. If we request the URLs now282we would only get an exception that Flask cannot find the templates.346we 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>
15 unmodified lines
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 %}316 {% if g.logged_in %}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>
14 unmodified lines
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 %}
8 unmodified lines
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.
modified:examples/flaskr/static/style.css+17 added-16 removed
modified:examples/flaskr/templates/show_entries.html+1 added-1 removed
modified:examples/flaskr/flaskr_tests.py+5 added-3 removed
31 unmodified lines
32 return self.app.get('/logout', follow_redirects=True)3334 # testing functions3536 def test_empty_db(self):37 """Start with a blank database."""38 rv = self.app.get('/')39 assert 'No entries here so far' in rv.data4041 def test_login_logout(self):42 """Make sure login and logout works"""43 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)44 assert 'You were logged in' in rv.data
5 unmodified lines
50 assert 'Invalid password' in rv.data5152 def test_messages(self):53 """Test that messages work"""49 # start with a blank state50 rv = self.app.get('/')51 assert 'No entries here so far' in rv.data54 self.login(flaskr.USERNAME, flaskr.PASSWORD)55 rv = self.app.post('/add', data=dict(56 title='<Hello>',57 text='<strong>HTML</strong> allowed here'
9 unmodified lines