Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

118 lines · 4.6 KiB

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 6–8why, one step back
6Now that the database connections are working, you can start writing the
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`.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 9–15why, 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 rows

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 21–32why, one step back
21
22 @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 only

Merge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49

line 33why, one step back
33responds to ``POST`` requests; the actual form is shown on the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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``).

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 51–63why, 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 the

Merge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49

line 64why, one step back
64`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 65why, one step back
65key is set to ``True``, and the user is redirected back to the `show_entries`

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 66–83why, one step back
66page. In addition, a message is flashed that informs the user that he or
67she 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)83

Merge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 90–98why, 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'))98

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 99–115why, one step back
99.. admonition:: Security Note
100101 Passwords should never be stored in plain text in a production102 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.106107 Fortunately, there are Flask extensions for the purpose of108 hashing passwords and verifying passwords against hashes, so adding109 this functionality is fairly straight forward. There are also110 many general python libraries that can be used for hashing.111112 You can find a list of recommended Flask extensions113 `here <http://flask.pocoo.org/extensions/>`_114115

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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