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 fileTake it
The walk stopped after 200 commits: lines older than 221aaa5 point at it.
Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 1–2why, one step back1.. _tutorial-views:2resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 3why, one step back3Step 6: The View FunctionsMerge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 4–5why, one step back4==========================5resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 6–8why, one step back6Now that the database connections are working, you can start writing the7view functions. You will need four of them; Show Entries, Add New Entry,8Login and Logout. Add the following code snipets to :file:`flaskr.py`.Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 9–15why, one step back910Show 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 rowsresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 16why, one step back16returned from the cursor look a bit like dictionaries because we are usingMerge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 17–18why, one step back17the :class:`sqlite3.Row` row factory.18resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 19–20why, one step back19The view function will pass the entries to the :file:`show_entries.html`20template and return the rendered one::Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 21–32why, one step back2122 @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 onlyMerge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49
line 33why, one step back33responds to ``POST`` requests; the actual form is shown on theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 34why, one step back34`show_entries` page. If everything worked out well, it willMerge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 35–48why, one step back35:func:`~flask.flash` an information message to the next request and36redirect 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'))48resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 49–50why, one step back49Note that this view checks that the user is logged in (that is, if the50`logged_in` key is present in the session and ``True``).Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 51–63why, one step back5152.. 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 theMerge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49
line 64why, one step back64`logged_in` key for the session. If the user logged in successfully, thatMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 65why, one step back65key is set to ``True``, and the user is redirected back to the `show_entries`Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 66–83why, one step back66page. 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)83Merge pull request #1277 from iKevinY/doc-fixesMarkus Unterwaditzerbefore adoption82d7c49
line 84why, one step back84The `logout` function, on the other hand, removes that key from the sessionresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 85why, one step back85again. There is a neat trick here: if you use the :meth:`~dict.pop` methodMerge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 86–87why, one step back86of the dict and pass a second parameter to it (the default), the method87will delete the key from the dictionary if present or do nothing when thatresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 88–89why, one step back88key is not in there. This is helpful because now it is not necessary to89check if the user was logged in.Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
lines 90–98why, one step back9091::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'))98resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 99–115why, one step back99.. admonition:: Security Note100101 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/>`_114115Merge pull request #1122 from milesrichardson/masterDaniel Neuhäuserbefore adoption221aaa5
line 116why, one step back116Continue with :ref:`tutorial-templates`.resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 117–118why, one step back117118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/