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
Provenance
- Commit
6dd92ae- Tree
b43dd34- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1246f40
7 files changed+306 added−92 removed
modified:docs/patterns.rst+2 added
38 unmodified lines39 def after_request(response):40 g.db.close()41 return response42 43+.. _easy-querying:44+45 Easy Querying46 `````````````47 48 Now in each request handling function you can access `g.db` to get the204 unmodified linesmodified:docs/quickstart.rst+8 added
87 unmodified lines88 app.run(debug=True)89 90 Both will have exactly the same effect.91 92+.. admonition:: Attention93 94+ 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.99+100+101 Routing102 -------103 104 As you have seen above, the :meth:`~flask.Flask.route` decorator is used520 unmodified linesmodified:docs/testing.rst+114 added-43 removed
20 unmodified lines21 22 The Application23 ---------------24 25-First we need an application to test for functionality. Let's start26-simple with a Hello World application (`hello.py`)::25+First we need an application to test for functionality. For the testing26+we will use the application from the :ref:`tutorial`. If you don't have27+that application yet, get the sources from `the examples`_.28 28- from flask import Flask, render_template_string29- app = Flask(__name__)29+.. _the examples:30+ http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/31 31- @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)39-32 The Testing Skeleton33 --------------------34 35 In 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::37 38 import unittest47- import hello39+ import flaskr40+ import tempfile41 49- class HelloWorldTestCase(unittest.TestCase):42+ class FlaskrTestCase(unittest.TestCase):43 44 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()49 50 if __name__ == '__main__':51 unittest.main()52 57-The code in the `setUp` function creates a new test client. That function58-is called before each individual test function. What the test client does59-for us is giving us a simple interface to the application. We can trigger60-test requests to the application and the client will also keep track of61-cookies for us.53+The code in the `setUp` function creates a new test client and initialize54+a new database. That function is called before each individual test function.55+What the test client does for us is giving us a simple interface to the56+application. We can trigger test requests to the application and the57+client will also keep track of cookies for us.58 59+Because SQLite3 is filesystem based we can easily use the tempfile module60+to create a temporary database and initialize it. Just make sure that you61+keep a reference to the :class:`~tempfile.NamedTemporaryFile` around (we62+store it as `self.db` because of that) so that the garbage collector does63+not remove that object and with it the database from the filesystem.64+65 If we now run that testsuite, we should see the following output::66 65- $ python hello_tests.py67+ $ python flaskr_tests.py68 69 ----------------------------------------------------------------------70 Ran 0 tests in 0.000s71 72 OK73 72-Even though it did not run any tests, we already know that our hello74+Even though it did not run any tests, we already know that our flaskr75 application is syntactically valid, otherwise the import would have died76 with an exception.77 78 The First Test79 --------------80 79-Now we can add the first test. Let's check that the application greets us80-with "Hello World" if we access it on ``/``. For that we modify our81-created test case class so that it looks like this::81+Now 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 (``/``).83+For that we modify our created test case class so that it looks like84+this::85 83- class HelloWorldTestCase(unittest.TestCase):86+ class FlaskrTestCase(unittest.TestCase):87 88 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()93 88- 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.data97 98 Test functions begin with the word `test`. Every function named like that99 will be picked up automatically. By using `self.app.get` we can send an100 HTTP `GET` request to the application with the given path. The return101 value will be a :class:`~flask.Flask.response_class` object. We can now102 use the :attr:`~werkzeug.BaseResponse.data` attribute to inspect the103 return value (as string) from the application. In this case, we ensure98-that ``'Hello World!'`` is part of the output.104+that ``'No entries here so far'`` is part of the output.105 100-Run it again and you should see one passing test. Let's add a second test101-here::106+Run it again and you should see one passing test::107 103- 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.034s112 107-Of course you can submit forms with the test client as well. For that and108-other features of the test client, check the documentation of the Werkzeug109-test :class:`~werkzeug.Client` and the tests of the MiniTwit example110-application:113+ OK114 112-- Werkzeug Test :class:`~werkzeug.Client`113-- `MiniTwit Example`_115+Of course you can submit forms with the test client as well which we will116+use now to log our user in.117 118+Logging In and Out119+------------------120+121+The majority of the functionality of our application is only available for122+the administration user. So we need a way to log our test client into the123+application and out of it again. For that we fire some requests to the124+login and logout pages with the required form data (username and125+password). Because the login and logout pages redirect, we tell the126+client to `follow_redirects`.127+128+Add the following two methods do your `FlaskrTestCase` class::129+130+ def login(self, username, password):131+ return self.app.post('/login', data=dict(132+ username=username,133+ password=password134+ ), follow_redirects=True)135+136+ def logout(self):137+ return self.app.get('/logout', follow_redirects=True)138+139+Now we can easily test if logging in and out works and that it fails with140+invalid credentials. Add this as new test to the class::141+142+ 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.data151+152+Test Adding Messages153+--------------------154+155+Now we can also test that adding messages works. Add a new test method156+like this::157+158+ 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 '<Hello>' in rv.data167+ assert '<strong>HTML</strong> allowed here' in rv.data168+169+Here we also check that HTML is allowed in the text but not in the title170+which is the intended behavior.171+172+Running that should now give us three passing tests::173+174+ $ python flaskr_tests.py 175+ ...176+ ----------------------------------------------------------------------177+ Ran 3 tests in 0.332s178+ 179+ OK180+181+For more complex tests with headers and status codes, check out the182+`MiniTwit Example`_ from the sources. That one contains a larger test183+suite.184+185+186 .. _MiniTwit Example:187 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/modified:docs/tutorial.rst+159 added-29 removed
29 unmodified lines30 is not sanitized because we trust the user here.31 3. the page shows all entries so far in reverse order (newest on top) and32 the user can add new ones from there if logged in.33 34+We will be using SQlite3 directly for that application because it's good35+enough for an application of that size. For larger applications however36+it makes a lot of sense to use `SQLAlchemy`_ that handles database37+connections in a more intelligent way, allows you to target different38+relational databases at once and more. You might also want to consider39+one of the popular NoSQL databases if your data is more suited for those.40+41 Here a screenshot from the final application:42 43 .. image:: _static/flaskr.png44 :align: center45 :class: screenshot46 :alt: screenshot of the final application47 48+.. _SQLAlchemy: http://www.sqlalchemy.org/49+50 Step 0: Creating The Folders51 ----------------------------52 53 Before we get started, let's create the folders needed for this4 unmodified lines58 /templates59 60 The `flaskr` folder is not a python package, but just something where we61 drop our files. Directly into this folder we will then put our database53-schema as well as main module in the following steps.62+schema as well as main module in the following steps. The files inside63+the `static` folder are available to users of the application via `HTTP`.64+This is the place where css and javascript files go. Inside the65+`templates` folder Flask will look for `Jinja2`_ templates. Drop all the66+templates there.67 68+.. _Jinja2: http://jinja.pocoo.org/2/69+70 Step 1: Database Schema71 -----------------------72 73 First we want to create the database schema. For this application only a19 unmodified lines93 ------------------------------94 95 Now that we have the schema in place we can create the application module.96 Let's call it `flaskr.py` inside the `flaskr` folder. For starters we82-will add the imports we will need as well as the config section::97+will add the imports we will need as well as the config section. For98+small applications it's a possibility to drop the configuration directly99+into the module which we will be doing here. However a cleaner solution100+would be to create a separate `.ini` or `.py` file and load that or import101+the values from there.102 103+::104+105 # all the imports106 import 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, flash109 110 # configuration111 DATABASE = '/tmp/flaskr.db'112 DEBUG = True113 SECRET_KEY = 'development key'114 USERNAME = 'admin'115 PASSWORD = 'default'116 96-The `with_statement` and :func:`~contextlib.closing` function are used to97-make dealing with the database connection easier later on for setting up98-the initial database. Next we can create our actual application and99-initialize it with the config::117+Next we can create our actual application and initialize it with the118+config::119 120 # create our little application :)121 app = Flask(__name__)122 app.secret_key = SECRET_KEY123 app.debug = DEBUG124 106-We can also add a method to easily connect to the database sepcified::125+The `secret_key` is needed to keep the client-side sessions secure.126+Choose that key wisely and as hard to guess and complex as possible. The127+debug flag enables or disables the interactive debugger. Never leave128+debug mode activated in a production system because it will allow users to129+executed code on the server!130 131+We also add a method to easily connect to the database specified. That132+can be used to open a connection on request and also from the interactive133+Python shell or a script. This will come in handy later134+135+::136+137 def connect_db():138 return sqlite3.connect(DATABASE)139 140 Finally we just add a line to the bottom of the file that fires up the1 unmodified line142 143 if __name__ == '__main__':144 app.run()145 146+With that out of the way you should be able to start up the application147+without problems. When you head over to the server you will get an 404148+page not found error because we don't have any views yet. But we will149+focus on that a little later. First we should get the database working.150+151 .. admonition:: Troubleshooting152 153 If you notice later that the browser cannot connect to the server154 during development, you might want to try this line instead::3 unmodified lines158 In a nutshell: Werkzeug starts up as IPv6 on many operating systems by159 default and not every browser is happy with that. This forces IPv4160 usage.161 128-With that out of the way you should be able to start up the application129-without problems. When you head over to the server you will get an 404130-page not found error because we don't have any views yet. But we will131-focus on that a little later. First we should get the database working.132-162 Step 3: Creating The Database163 -----------------------------164 165 Flaskr is a database powered application as outlined earlier, and more21 unmodified lines187 from __future__ import with_statement188 from contextlib import closing189 190 Next we can create a function called `init_db` that initializes the162-database::191+database. For this we can use the `connect_db` function we defined192+earlier. Just add that function below the `connect_db` function::193 194 def init_db():195 with closing(connect_db()) as db:196 with app.open_resource('schema.sql') as f:197 db.cursor().executescript(f.read())198 db.commit()199 200+The :func:`~contextlib.closing` helper function allows us to keep a201+connection open for the duration of the `with` block. The202+:func:`~flask.Flask.open_resource` method of the application object203+supports that functionality out of the box, so it can be used in the204+`with` block directly. This function opens a file from the resource205+location (your `flaskr` folder) and allows you to read from it. We are206+using this here to execute a script on the database connection.207+208+When we connect to a database we get a connection object (here called209+`db`) that can give us a cursor. On that cursor there is a method to210+execute a complete script. Finally we only have to commit the changes.211+SQLite 3 and other transactional databases will not commit unless you212+explicitly tell it to.213+214 Now it is possible to create a database by starting up a Python shell and215 importing and calling that function::216 217 >>> from flaskr import init_db218 >>> init_db()219 176-The :meth:`~flask.Flask.open_resource` function opens a file from the177-resource location (your flaskr folder) and allows you to read from it. We178-are using this here to execute a script on the database connection.179-180-When 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 to182-execute a complete script. Finally we only have to commit the changes and183-close the transaction.184-220 Step 4: Request Database Connections221 ------------------------------------222 223 Now we know how we can open database connections and use them for scripts,35 unmodified lines259 260 Show Entries261 ````````````262 228-This view shows all the entries stored in the database::263+This view shows all the entries stored in the database. It listens on the264+root of the application and will select title and text from the database.265+The one with the highest id (the newest entry) on top. The rows returned266+from the cursor are tuples with the columns ordered like specified in the267+select statement. This is good enough for small applications like here,268+but you might want to convert them into a dict. If you are interested how269+to do that, check out the :ref:`easy-querying` example.270 271+The view function will pass the entries as dicts to the272+`show_entries.html` template and return the rendered one::273+274 @app.route('/')275 def show_entries():276 cur = g.db.execute('select title, text from entries order by id desc')277 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]3 unmodified lines281 `````````````282 283 This view lets the user add new entries if he's logged in. This only284 responds to `POST` requests, the actual form is shown on 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 and287+redirect back to the `show_entries` page::288 289 @app.route('/add', methods=['POST'])290 def add_entry():291 if not session.get('logged_in'):3 unmodified lines295 g.db.commit()296 flash('New entry was successfully posted')297 return redirect(url_for('show_entries'))298 299+Note that we check that the user is logged in here (the `logged_in` key is300+present in the session and `True`).301+302 Login and Logout303 ````````````````304 256-These functions are used to sign the user in and out::305+These functions are used to sign the user in and out. Login checks the306+username and password against the ones from the configuration and sets the307+`logged_in` key in the session. If the user logged in successfully that308+key is set to `True` and the user is redirected back to the `show_entries`309+page. In that case also a message is flashed that informs the user he or310+she was logged in successfully. If an error occoured the template is311+notified about that and the user asked again::312 313 @app.route('/login', methods=['GET', 'POST'])314 def login():315 error = None7 unmodified lines323 flash('You were logged in')324 return redirect(url_for('show_entries'))325 return render_template('login.html', error=error)326 327+The logout function on the other hand removes that key from the session328+again. We use a neat trick here: if you use the :meth:`~dict.pop` method329+of the dict and pass a second parameter to it (the default) the method330+will delete the key from the dictionary if present or do nothing when that331+key was not in there. This is helpful because we don't have to check in332+that case if the user was logged in.333+334+::335+336 @app.route('/logout')337 def logout():338 session.pop('logged_in', None)339 flash('You were logged out')2 unmodified lines342 Step 6: The Templates343 ---------------------344 345 Now we should start working on the templates. If we request the URLs now282-we would only get an exception that Flask cannot find the templates.346+we would only get an exception that Flask cannot find the templates. The347+templates are using `Jinja2`_ syntax and have autoescaping enabled by348+default. This means that unless you mark a value in the code with349+:class:`~flask.Markup` or with the ``|safe`` filter in the template,350+Jinja2 will ensure that special characters such as ``<`` or ``>`` are351+escaped with their XML equivalents.352 353+We are also using template inheritance which makes it possible to reuse354+the layout of the website in all pages.355+356 Put the following templates into the `templates` folder:357 358 layout.html359 ```````````360 361+This template contains the HTML skeleton, the header and a link to log in362+(or log out if the user was already logged in). It also displays the363+flashed messages if there are any. The ``{% block body %}`` block can be364+replaced by a block of the same name (``body``) in a child template.365+366+The :class:`~flask.session` dict is available in the template as well and367+you can use that to check if the user is logged in or not. Note that in368+Jinja you can access missing attributes and items of objects / dicts which369+makes the following code work, even if there is no ``'logged_in'`` key in370+the session:371+372 .. sourcecode:: html+jinja373 374 <!doctype html>375 <title>Flaskr</title>15 unmodified lines391 392 show_entries.html393 `````````````````394 395+This template extends the `layout.html` template from above to display the396+messages. Note that the `for` loop iterates over the messages we passed397+in with the :func:`~flask.render_template` function. We also tell the398+form to submit to your `add_entry` function and use `POST` as `HTTP`399+method:400+401 .. sourcecode:: html+jinja402 403 {% extends "layout.html" %}404 {% block body %}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 lines424 425 login.html426 ``````````427 428+Finally the login template which basically just displays a form to allow429+the user to login:430+431 .. sourcecode:: html+jinja432 433 {% extends "layout.html" %}434 {% block body %}8 unmodified lines443 <dd><input type=submit value=Login>444 </dl>445 </form>446 {% endblock %}447+448+Step 7: Adding Style449+--------------------450+451+Now that everything else works, it's time to add some style to the452+application. Just create a stylesheet called `style.css` in the `static`453+folder we created before:454+455+.. sourcecode:: css456+457+ body { font-family: sans-serif; background: #eee; }458+ a, h1, h2 { color: #377BA8; }459+ h1, h2 { font-family: 'Georgia', serif; margin: 0; }460+ h1 { border-bottom: 2px solid #eee; }461+ h2 { font-size: 1.2em; }462+ 463+ .page { margin: 2em auto; width: 35em; border: 5px solid #ccc;464+ padding: 0.8em; background: white; }465+ .entries { list-style: none; margin: 0; padding: 0; }466+ .entries li { margin: 0.8em 1.2em; }467+ .entries li h2 { margin-left: -1em; }468+ .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }469+ .add-entry dl { font-weight: bold; }470+ .metanav { text-align: right; font-size: 0.8em; padding: 0.3em;471+ margin-bottom: 1em; background: #fafafa; }472+ .flash { background: #CEE5F5; padding: 0.5em;473+ border: 1px solid #AACBE2; }474+ .error { background: #F0D6D6; padding: 0.5em; }475+476+Bonus: Testing the Application477+-------------------------------478+479+Now that you have finished the application and everything works as480+expected, it's probably not the best idea to add automated tests to481+simplify modifications in the future. The application above is used as a482+basic example of how to perform unittesting in the :ref:`testing` section483+of the documentation. Go there to see how easy it is to test Flask484+applications.modified:examples/flaskr/static/style.css+17 added-16 removed
123451234567891011121314151617789101112131415161718body { font-family: sans-serif; background: #eee; }a, h1, h2 { color: #377BA8; }h1, h2 { font-family: 'Georgia', serif; margin: 0; }h1 { border-bottom: 2px solid #eee; }h2 { font-size: 1.2em; }body { font-family: sans-serif; background: #eee; }a, h1, h2 { color: #377BA8; }h1, h2 { font-family: 'Georgia', serif; margin: 0; }h1 { border-bottom: 2px solid #eee; }h2 { font-size: 1.2em; }
div.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; }ul.entries { list-style: none; margin: 0; padding: 0; }ul.entries li { margin: 0.8em 1.2em; }ul.entries li h2 { margin-left: -1em; }form.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }form.add-entry dl { font-weight: bold; }div.metanav { text-align: right; font-size: 0.8em; background: #fafafa; padding: 0.3em; margin-bottom: 1em; }div.flash { background: #CEE5F5; padding: 0.5em; border: 1px solid #AACBE2; }p.error { background: #F0D6D6; padding: 0.5em; }.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; }.entries { list-style: none; margin: 0; padding: 0; }.entries li { margin: 0.8em 1.2em; }.entries li h2 { margin-left: -1em; }.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }.add-entry dl { font-weight: bold; }.metanav { text-align: right; font-size: 0.8em; padding: 0.3em; margin-bottom: 1em; background: #fafafa; }.flash { background: #CEE5F5; padding: 0.5em; border: 1px solid #AACBE2; }.error { background: #F0D6D6; padding: 0.5em; }modified:examples/flaskr/templates/show_entries.html+1 added-1 removed
1233456714 unmodified lines{% extends "layout.html" %}{% block body %} {% if g.logged_in %} {% if session.logged_in %} <form action="{{ url_for('add_entry') }}" method=post class=add-entry> <dl> <dt>Title: <dd><input type=text size=30 name=title>14 unmodified linesmodified:examples/flaskr/flaskr_tests.py+5 added-3 removed
31 unmodified lines32 return self.app.get('/logout', follow_redirects=True)33 34 # testing functions35 36+ 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.data40+41 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.data5 unmodified lines50 assert 'Invalid password' in rv.data51 52 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