Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

118 lines · 4.6 KiB

Last changed by

Minor edits to tutorial for clarity. (#2330)Dave Morsebefore adoption50c6df7

History of this file

Take it

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Minor edits to tutorial for clarity. (#2330)Dave Morsebefore adoption50c6df7

lines 7–8why, one step back
7view functions. You will need four of them; Show Entries, Add New Entry,
8Login and Logout. Add the following code snipets to :file:`flaskr.py`.

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 9–33why, one step back
9
10Show Entries11------------1213This view shows all the entries stored in the database. It listens on the14root of the application and will select title and text from the database.15The one with the highest id (the newest entry) will be on top. The rows16returned from the cursor look a bit like dictionaries because we are using17the :class:`sqlite3.Row` row factory.1819The view function will pass the entries to the :file:`show_entries.html`20template and return the rendered one::2122 @app.route('/')23 def show_entries():24 db = get_db()25 cur = db.execute('select title, text from entries order by id desc')26 entries = cur.fetchall()27 return render_template('show_entries.html', entries=entries)2829Add New Entry30-------------3132This view lets the user add new entries if they are logged in. This only33responds to ``POST`` requests; the actual form is shown on the

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 35–48why, one step back
35:func:`~flask.flash` an information message to the next request and
36redirect back to the `show_entries` page::3738 @app.route('/add', methods=['POST'])39 def add_entry():40 if not session.get('logged_in'):41 abort(401)42 db = get_db()43 db.execute('insert into entries (title, text) values (?, ?)',44 [request.form['title'], request.form['text']])45 db.commit()46 flash('New entry was successfully posted')47 return redirect(url_for('show_entries'))48

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 51–84why, one step back
51
52.. admonition:: Security Note5354 Be sure to use question marks when building SQL statements, as done in the55 example above. Otherwise, your app will be vulnerable to SQL injection when56 you use string formatting to build SQL statements.57 See :ref:`sqlite3` for more.5859Login and Logout60----------------6162These functions are used to sign the user in and out. Login checks the63username and password against the ones from the configuration and sets the64`logged_in` key for the session. If the user logged in successfully, that65key is set to ``True``, and the user is redirected back to the `show_entries`66page. In addition, a message is flashed that informs the user that he or67she was logged in successfully. If an error occurred, the template is68notified about that, and the user is asked again::6970 @app.route('/login', methods=['GET', 'POST'])71 def login():72 error = None73 if request.method == 'POST':74 if request.form['username'] != app.config['USERNAME']:75 error = 'Invalid username'76 elif request.form['password'] != app.config['PASSWORD']:77 error = 'Invalid password'78 else:79 session['logged_in'] = True80 flash('You were logged in')81 return redirect(url_for('show_entries'))82 return render_template('login.html', error=error)8384The `logout` function, on the other hand, removes that key from the session

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 90–100why, one step back
90
91::9293 @app.route('/logout')94 def logout():95 session.pop('logged_in', None)96 flash('You were logged out')97 return redirect(url_for('show_entries'))9899.. admonition:: Security Note100

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 106why, one step back
106

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge branch '0.11-maintenance'David Lordbefore adoption633b13e

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 113–118why, one step back
113 `here <http://flask.pocoo.org/extensions/>`_
114115116Continue with :ref:`tutorial-templates`.117118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/