Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

301 lines · 10.6 KiB

Last changed by

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

History of this file

Take it

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

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 1why, one step back
1.. currentmodule:: flask

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 2why, one step back
2

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 3–4why, one step back
3Blueprints and Views
4====================

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 5why, one step back
5

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 6–10why, one step back
6A view function is the code you write to respond to requests to your
7application. Flask uses patterns to match the incoming request URL to8the view that should handle it. The view returns data that Flask turns9into an outgoing response. Flask can also go the other direction and10generate a URL to a view based on its name and arguments.

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

lines 11–12why, one step back
11
12

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 13–14why, one step back
13Create a Blueprint
14------------------

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 15why, one step back
15

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 16–20why, one step back
16A :class:`Blueprint` is a way to organize a group of related views and
17other code. Rather than registering views and other code directly with18an application, they are registered with a blueprint. Then the blueprint19is registered with the application when it is available in the factory20function.

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 21why, one step back
21

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 22–25why, one step back
22Flaskr will have two blueprints, one for authentication functions and
23one for the blog posts functions. The code for each blueprint will go24in a separate module. Since the blog needs to know about authentication,25you'll write the authentication one first.

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 26why, one step back
26

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 27–28why, one step back
27.. code-block:: python
28 :caption: ``flaskr/auth.py``

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 29why, one step back
29

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 30why, one step back
30 import functools

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 31why, one step back
31

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 32–35why, one step back
32 from flask import (
33 Blueprint, flash, g, redirect, render_template, request, session, url_for34 )35 from werkzeug.security import check_password_hash, generate_password_hash

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 36why, one step back
36

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 37why, one step back
37 from flaskr.db import get_db

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 38why, one step back
38

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 39why, one step back
39 bp = Blueprint('auth', __name__, url_prefix='/auth')

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 40why, one step back
40

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 41–44why, one step back
41This creates a :class:`Blueprint` named ``'auth'``. Like the application
42object, the blueprint needs to know where it's defined, so ``__name__``43is passed as the second argument. The ``url_prefix`` will be prepended44to all the URLs associated with the blueprint.

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 45why, one step back
45

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 46–48why, one step back
46Import and register the blueprint from the factory using
47:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the48new code at the end of the factory function before returning the app.

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 49why, one step back
49

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 50–51why, one step back
50.. code-block:: python
51 :caption: ``flaskr/__init__.py``

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 52why, one step back
52

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 53–174why, one step back
53 def create_app():
54 app = ...55 # existing code omitted5657 from . import auth58 app.register_blueprint(auth.bp)5960 return app6162The authentication blueprint will have views to register new users and63to log in and log out.646566The First View: Register67------------------------6869When the user visits the ``/auth/register`` URL, the ``register`` view70will return `HTML`_ with a form for them to fill out. When they submit71the form, it will validate their input and either show the form again72with an error message or create the new user and go to the login page.7374.. _HTML: https://developer.mozilla.org/docs/Web/HTML7576For now you will just write the view code. On the next page, you'll77write templates to generate the HTML form.7879.. code-block:: python80 :caption: ``flaskr/auth.py``8182 @bp.route('/register', methods=('GET', 'POST'))83 def register():84 if request.method == 'POST':85 username = request.form['username']86 password = request.form['password']87 db = get_db()88 error = None8990 if not username:91 error = 'Username is required.'92 elif not password:93 error = 'Password is required.'94 elif db.execute(95 'SELECT id FROM user WHERE username = ?', (username,)96 ).fetchone() is not None:97 error = 'User {} is already registered.'.format(username)9899 if error is None:100 db.execute(101 'INSERT INTO user (username, password) VALUES (?, ?)',102 (username, generate_password_hash(password))103 )104 db.commit()105 return redirect(url_for('auth.login'))106107 flash(error)108109 return render_template('auth/register.html')110111Here's what the ``register`` view function is doing:112113#. :meth:`@bp.route <Blueprint.route>` associates the URL ``/register``114 with the ``register`` view function. When Flask receives a request115 to ``/auth/register``, it will call the ``register`` view and use116 the return value as the response.117118#. If the user submitted the form,119 :attr:`request.method <Request.method>` will be ``'POST'``. In this120 case, start validating the input.121122#. :attr:`request.form <Request.form>` is a special type of123 :class:`dict` mapping submitted form keys and values. The user will124 input their ``username`` and ``password``.125126#. Validate that ``username`` and ``password`` are not empty.127128#. Validate that ``username`` is not already registered by querying the129 database and checking if a result is returned.130 :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL query131 with ``?`` placeholders for any user input, and a tuple of values132 to replace the placeholders with. The database library will take133 care of escaping the values so you are not vulnerable to a134 *SQL injection attack*.135136 :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.137 If the query returned no results, it returns ``None``. Later,138 :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of139 all results.140141#. If validation succeeds, insert the new user data into the database.142 For security, passwords should never be stored in the database143 directly. Instead,144 :func:`~werkzeug.security.generate_password_hash` is used to145 securely hash the password, and that hash is stored. Since this146 query modifies data, :meth:`db.commit() <sqlite3.Connection.commit>`147 needs to be called afterwards to save the changes.148149#. After storing the user, they are redirected to the login page.150 :func:`url_for` generates the URL for the login view based on its151 name. This is preferable to writing the URL directly as it allows152 you to change the URL later without changing all code that links to153 it. :func:`redirect` generates a redirect response to the generated154 URL.155156#. If validation fails, the error is shown to the user. :func:`flash`157 stores messages that can be retrieved when rendering the template.158159#. When the user initially navigates to ``auth/register``, or160 there was an validation error, an HTML page with the registration161 form should be shown. :func:`render_template` will render a template162 containing the HTML, which you'll write in the next step of the163 tutorial.164165166Login167-----168169This view follows the same pattern as the ``register`` view above.170171.. code-block:: python172 :caption: ``flaskr/auth.py``173174 @bp.route('/login', methods=('GET', 'POST'))

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

lines 175–176why, one step back
175 def login():
176 if request.method == 'POST':

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 177–183why, one step back
177 username = request.form['username']
178 password = request.form['password']179 db = get_db()180 error = None181 user = db.execute(182 'SELECT * FROM user WHERE username = ?', (username,)183 ).fetchone()

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 184why, one step back
184

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 185–188why, one step back
185 if user is None:
186 error = 'Incorrect username.'187 elif not check_password_hash(user['password'], password):188 error = 'Incorrect password.'

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 189why, one step back
189

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 190–193why, one step back
190 if error is None:
191 session.clear()192 session['user_id'] = user['id']193 return redirect(url_for('index'))

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 194why, one step back
194

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 195–250why, one step back
195 flash(error)
196197 return render_template('auth/login.html')198199There are a few differences from the ``register`` view:200201#. The user is queried first and stored in a variable for later use.202203#. :func:`~werkzeug.security.check_password_hash` hashes the submitted204 password in the same way as the stored hash and securely compares205 them. If they match, the password is valid.206207#. :data:`session` is a :class:`dict` that stores data across requests.208 When validation succeeds, the user's ``id`` is stored in a new209 session. The data is stored in a *cookie* that is sent to the210 browser, and the browser then sends it back with subsequent requests.211 Flask securely *signs* the data so that it can't be tampered with.212213Now that the user's ``id`` is stored in the :data:`session`, it will be214available on subsequent requests. At the beginning of each request, if215a user is logged in their information should be loaded and made216available to other views.217218.. code-block:: python219 :caption: ``flaskr/auth.py``220221 @bp.before_app_request222 def load_logged_in_user():223 user_id = session.get('user_id')224225 if user_id is None:226 g.user = None227 else:228 g.user = get_db().execute(229 'SELECT * FROM user WHERE id = ?', (user_id,)230 ).fetchone()231232:meth:`bp.before_app_request() <Blueprint.before_app_request>` registers233a function that runs before the view function, no matter what URL is234requested. ``load_logged_in_user`` checks if a user id is stored in the235:data:`session` and gets that user's data from the database, storing it236on :data:`g.user <g>`, which lasts for the length of the request. If237there is no user id, or if the id doesn't exist, ``g.user`` will be238``None``.239240241Logout242------243244To log out, you need to remove the user id from the :data:`session`.245Then ``load_logged_in_user`` won't load a user on subsequent requests.246247.. code-block:: python248 :caption: ``flaskr/auth.py``249250 @bp.route('/logout')

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 251why, one step back
251 def logout():

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 252–253why, one step back
252 session.clear()
253 return redirect(url_for('index'))

Merge branch 'flask_deployment_docs'Markus Unterwaditzerbefore adoptionf166894

line 254why, one step back
254

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 255why, one step back
255

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 256–257why, one step back
256Require Authentication in Other Views
257-------------------------------------

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 258why, one step back
258

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 259–261why, one step back
259Creating, editing, and deleting blog posts will require a user to be
260logged in. A *decorator* can be used to check this for each view it's261applied to.

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 262why, one step back
262

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 263–264why, one step back
263.. code-block:: python
264 :caption: ``flaskr/auth.py``

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 265why, one step back
265

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 266–270why, one step back
266 def login_required(view):
267 @functools.wraps(view)268 def wrapped_view(**kwargs):269 if g.user is None:270 return redirect(url_for('auth.login'))

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 271why, one step back
271

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 272why, one step back
272 return view(**kwargs)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 273why, one step back
273

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

lines 274–301why, one step back
274 return wrapped_view
275276This decorator returns a new view function that wraps the original view277it's applied to. The new function checks if a user is loaded and278redirects to the login page otherwise. If a user is loaded the original279view is called and continues normally. You'll use this decorator when280writing the blog views.281282Endpoints and URLs283------------------284285The :func:`url_for` function generates the URL to a view based on a name286and arguments. The name associated with a view is also called the287*endpoint*, and by default it's the same as the name of the view288function.289290For example, the ``hello()`` view that was added to the app291factory earlier in the tutorial has the name ``'hello'`` and can be292linked to with ``url_for('hello')``. If it took an argument, which293you'll see later, it would be linked to using294``url_for('hello', who='World')``.295296When using a blueprint, the name of the blueprint is prepended to the297name of the function, so the endpoint for the ``login`` function you298wrote above is ``'auth.login'`` because you added it to the ``'auth'``299blueprint.300301Continue to :doc:`templates`.