Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

98 lines · 3.7 KiB

Last changed by

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

History of this file

Take it

The walk stopped after 200 commits: lines older than e562acf point at it.

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 1–5why, one step back
1.. _tutorial-views:
23Step 5: The View Functions4==========================5

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

line 6why, one step back
6Now that the database connections are working, we can start writing the

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 7–14why, one step back
7view functions. We will need four of them:
89Show Entries10------------1112This view shows all the entries stored in the database. It listens on the13root of the application and will select title and text from the database.14The one with the highest id (the newest entry) will be on top. The rows

Rewrote tutorial to use the g based appcontext objectArmin Ronacherbefore adoption05161d3

lines 15–16why, one step back
15returned from the cursor look a bit like tuples because we are using
16the :class:`sqlite3.Row` row factory.

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

line 17why, one step back
17

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

line 18why, one step back
18The view function will pass the entries as dictionaries to the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 19why, one step back
19:file:`show_entries.html` template and return the rendered one::

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 20–22why, one step back
20
21 @app.route('/')22 def show_entries():

Rewrote tutorial to use the g based appcontext objectArmin Ronacherbefore adoption05161d3

lines 23–25why, one step back
23 db = get_db()
24 cur = db.execute('select title, text from entries order by id desc')25 entries = cur.fetchall()

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 26–31why, one step back
26 return render_template('show_entries.html', entries=entries)
2728Add New Entry29-------------3031This view lets the user add new entries if they are logged in. This only

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

lines 32–33why, one step back
32responds to ``POST`` requests; the actual form is shown on the
33`show_entries` page. If everything worked out well, we will

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 34–40why, one step back
34:func:`~flask.flash` an information message to the next request and
35redirect back to the `show_entries` page::3637 @app.route('/add', methods=['POST'])38 def add_entry():39 if not session.get('logged_in'):40 abort(401)

Rewrote tutorial to use the g based appcontext objectArmin Ronacherbefore adoption05161d3

lines 41–42why, one step back
41 db = get_db()
42 db.execute('insert into entries (title, text) values (?, ?)',

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

line 43why, one step back
43 [request.form['title'], request.form['text']])

Rewrote tutorial to use the g based appcontext objectArmin Ronacherbefore adoption05161d3

line 44why, one step back
44 db.commit()

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 45–48why, one step back
45 flash('New entry was successfully posted')
46 return redirect(url_for('show_entries'))4748Note that we check that the user is logged in here (the `logged_in` key is

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 49why, one step back
49present in the session and ``True``).

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 50–62why, one step back
50
51.. admonition:: Security Note5253 Be sure to use question marks when building SQL statements, as done in the54 example above. Otherwise, your app will be vulnerable to SQL injection when55 you use string formatting to build SQL statements.56 See :ref:`sqlite3` for more.5758Login and Logout59----------------6061These functions are used to sign the user in and out. Login checks the62username and password against the ones from the configuration and sets the

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

line 63why, one step back
63`logged_in` key for the session. If the user logged in successfully, that

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 64why, one step back
64key is set to ``True``, and the user is redirected back to the `show_entries`

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 65–82why, one step back
65page. In addition, a message is flashed that informs the user that he or
66she was logged in successfully. If an error occurred, the template is67notified about that, and the user is asked again::6869 @app.route('/login', methods=['GET', 'POST'])70 def login():71 error = None72 if request.method == 'POST':73 if request.form['username'] != app.config['USERNAME']:74 error = 'Invalid username'75 elif request.form['password'] != app.config['PASSWORD']:76 error = 'Invalid password'77 else:78 session['logged_in'] = True79 flash('You were logged in')80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)82

Grammatical fixes in Foreword and TutorialKevin Yapbefore adoption23fc2e5

line 83why, one step back
83The `logout` function, on the other hand, removes that key from the session

Set release date for 0.10.1Armin Ronacherbefore adoptione562acf

lines 84–98why, one step back
84again. We use a neat trick here: if you use the :meth:`~dict.pop` method
85of the dict and pass a second parameter to it (the default), the method86will delete the key from the dictionary if present or do nothing when that87key is not in there. This is helpful because now we don't have to check88if the user was logged in.8990::9192 @app.route('/logout')93 def logout():94 session.pop('logged_in', None)95 flash('You were logged out')96 return redirect(url_for('show_entries'))9798Continue with :ref:`tutorial-templates`.