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

1.. _tutorial-views:23Step 6: The View Functions4==========================56Now 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`.910Show 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 the34`show_entries` page.  If everything worked out well, it will35: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'))4849Note that this view checks that the user is logged in (that is, if the50`logged_in` key is present in the session and ``True``).5152.. 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 session85again.  There is a neat trick here: if you use the :meth:`~dict.pop` method86of 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 that88key is not in there.  This is helpful because now it is not necessary to89check if the user was logged in.9091::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 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/>`_114115116Continue with :ref:`tutorial-templates`.117118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/