views.rst
This file
Path
docs/tutorial/views.rst
87 lines · 3.5 KiB
Last changed by
New style for the documentation. Looks more like the website now.Armin Ronacherbefore adoptionbcf347f
History of this fileTake it
New style for the documentation. Looks more like the website now.Armin Ronacherbefore adoptionbcf347f
lines 1–87why, one step back1Step 5: The View Functions2==========================34Now that the database connections are working we can start writing the5view functions. We will need four of them:67Show Entries8------------910This view shows all the entries stored in the database. It listens on the11root of the application and will select title and text from the database.12The one with the highest id (the newest entry) on top. The rows returned13from the cursor are tuples with the columns ordered like specified in the14select statement. This is good enough for small applications like here,15but you might want to convert them into a dict. If you are interested how16to do that, check out the :ref:`easy-querying` example.1718The view function will pass the entries as dicts to the19`show_entries.html` template and return the rendered one::2021 @app.route('/')22 def show_entries():23 cur = g.db.execute('select title, text from entries order by id desc')24 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]25 return render_template('show_entries.html', entries=entries)2627Add New Entry28-------------2930This view lets the user add new entries if he's logged in. This only31responds to `POST` requests, the actual form is shown on the32`show_entries` page. If everything worked out well we will33:func:`~flask.flash` an information message to the next request and34redirect back to the `show_entries` page::3536 @app.route('/add', methods=['POST'])37 def add_entry():38 if not session.get('logged_in'):39 abort(401)40 g.db.execute('insert into entries (title, text) values (?, ?)',41 [request.form['title'], request.form['text']])42 g.db.commit()43 flash('New entry was successfully posted')44 return redirect(url_for('show_entries'))4546Note that we check that the user is logged in here (the `logged_in` key is47present in the session and `True`).4849Login and Logout50----------------5152These functions are used to sign the user in and out. Login checks the53username and password against the ones from the configuration and sets the54`logged_in` key in the session. If the user logged in successfully that55key is set to `True` and the user is redirected back to the `show_entries`56page. In that case also a message is flashed that informs the user he or57she was logged in successfully. If an error occoured the template is58notified about that and the user asked again::5960 @app.route('/login', methods=['GET', 'POST'])61 def login():62 error = None63 if request.method == 'POST':64 if request.form['username'] != USERNAME:65 error = 'Invalid username'66 elif request.form['password'] != PASSWORD:67 error = 'Invalid password'68 else:69 session['logged_in'] = True70 flash('You were logged in')71 return redirect(url_for('show_entries'))72 return render_template('login.html', error=error)7374The logout function on the other hand removes that key from the session75again. We use a neat trick here: if you use the :meth:`~dict.pop` method76of the dict and pass a second parameter to it (the default) the method77will delete the key from the dictionary if present or do nothing when that78key was not in there. This is helpful because we don't have to check in79that case if the user was logged in.8081::8283 @app.route('/logout')84 def logout():85 session.pop('logged_in', None)86 flash('You were logged out')87 return redirect(url_for('show_entries'))