views.rst
This file
Path
docs/tutorial/views.rst
118 lines · 4.6 KiB
Last changed by
Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
History of this fileTake it
The walk stopped after 200 commits: lines older than da0ebb9 point at it.
Merge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
lines 1–2why, one step back1.. _tutorial-views:2Merge branch '0.11-maintenance'Markus Unterwaditzerbefore adoption7132feb
line 3why, one step back3Step 6: The View FunctionsMerge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
lines 4–5why, one step back4==========================5Merge branch '0.11-maintenance'David Lordbefore adoption633b13e
line 6why, one step back6Now that the database connections are working, you can start writing theMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 7–8why, one step back7view 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 #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
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 rowsminor revision of documentation.bagrattebefore adoption9a80fe6
line 16why, one step back16returned from the cursor look a bit like dictionaries because we are usingMerge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
lines 17–18why, one step back17the :class:`sqlite3.Row` row factory.18minor revision of documentation.bagrattebefore adoption9a80fe6
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 #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
lines 21–33why, 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 only33responds to ``POST`` requests; the actual form is shown on theMerge branch '0.11-maintenance'David Lordbefore adoption633b13e
line 34why, one step back34`show_entries` page. If everything worked out well, it willMerge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
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'))48Merge branch '0.11-maintenance'David Lordbefore adoption633b13e
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 #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
lines 51–84why, 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 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 sessionMerge branch '0.11-maintenance'David Lordbefore adoption633b13e
line 85why, one step back85again. There is a neat trick here: if you use the :meth:`~dict.pop` methodMerge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
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 thatMerge branch '0.11-maintenance'David Lordbefore adoption633b13e
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 #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
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'))98Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd
lines 99–100why, one step back99.. admonition:: Security Note100Merge branch '0.11-maintenance'David Lordbefore adoption633b13e
lines 101–105why, one step back101 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.Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd
line 106why, one step back106Merge branch '0.11-maintenance'David Lordbefore adoption633b13e
lines 107–109why, one step back107 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 alsoTutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd
lines 110–111why, one step back110 many general python libraries that can be used for hashing.111Merge branch '0.11-maintenance'David Lordbefore adoption633b13e
line 112why, one step back112 You can find a list of recommended Flask extensionsTutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd
lines 113–115why, one step back113 `here <http://flask.pocoo.org/extensions/>`_114115Merge pull request #1760 from mattrobenolt/patch-1Markus Unterwaditzerbefore adoptionda0ebb9
line 116why, one step back116Continue with :ref:`tutorial-templates`.Tutorial: Note extensions for encrypting passwords (#1854)wldtypbefore adoptionfa327fd
lines 117–118why, one step back117118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/