Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

117 lines · 4.5 KiB

Last changed by

Merge branch '0.11-maintenance'Markus Unterwaditzerbefore adoption7132feb

History of this file

Take it

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

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 1–2why, one step back
1.. _tutorial-views:
2

Merge branch '0.11-maintenance'Markus Unterwaditzerbefore adoption7132feb

line 3why, one step back
3Step 6: The View Functions

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 4–5why, one step back
4==========================
5

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

lines 6–7why, one step back
6Now that the database connections are working, you can start writing the
7view functions. You will need four of them:

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 8–14why, one step back
8
9Show 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

minor revision of documentation.bagrattebefore adoption9a80fe6

line 15why, one step back
15returned from the cursor look a bit like dictionaries because we are using

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 16–17why, one step back
16the :class:`sqlite3.Row` row factory.
17

minor revision of documentation.bagrattebefore adoption9a80fe6

lines 18–19why, one step back
18The view function will pass the entries to the :file:`show_entries.html`
19template and return the rendered one::

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 20–32why, one step back
20
21 @app.route('/')22 def show_entries():23 db = get_db()24 cur = db.execute('select title, text from entries order by id desc')25 entries = cur.fetchall()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 only32responds to ``POST`` requests; the actual form is shown on the

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

line 33why, one step back
33`show_entries` page. If everything worked out well, it will

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 34–47why, 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)41 db = get_db()42 db.execute('insert into entries (title, text) values (?, ?)',43 [request.form['title'], request.form['text']])44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))47

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

lines 48–49why, one step back
48Note that this view checks that the user is logged in (that is, if the
49`logged_in` key is present in the session and ``True``).

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 50–83why, 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 the63`logged_in` key for the session. If the user logged in successfully, that64key is set to ``True``, and the user is redirected back to the `show_entries`65page. In addition, a message is flashed that informs the user that he or66she 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)8283The `logout` function, on the other hand, removes that key from the session

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

line 84why, one step back
84again. There is a neat trick here: if you use the :meth:`~dict.pop` method

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 85–86why, one step back
85of the dict and pass a second parameter to it (the default), the method
86will delete the key from the dictionary if present or do nothing when that

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

lines 87–88why, one step back
87key is not in there. This is helpful because now it is not necessary to
88check if the user was logged in.

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

lines 89–97why, one step back
89
90::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'))97

Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd

lines 98–99why, one step back
98.. admonition:: Security Note
99

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

lines 100–104why, one step back
100 Passwords should never be stored in plain text in a production
101 system. This tutorial uses plain text passwords for simplicity. If you102 plan to release a project based off this tutorial out into the world,103 passwords should be both `hashed and salted`_ before being stored in a104 database or file.

Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd

line 105why, one step back
105

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

lines 106–108why, one step back
106 Fortunately, there are Flask extensions for the purpose of
107 hashing passwords and verifying passwords against hashes, so adding108 this functionality is fairly straight forward. There are also

Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd

lines 109–110why, one step back
109 many general python libraries that can be used for hashing.
110

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

line 111why, one step back
111 You can find a list of recommended Flask extensions

Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd

lines 112–114why, one step back
112 `here <http://flask.pocoo.org/extensions/>`_
113114

Clarify some docsMarkus Unterwaditzerbefore adoption0d19fa0

line 115why, one step back
115Continue with :ref:`tutorial-templates`.

Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd

lines 116–117why, one step back
116
117.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/