Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

301 lines · 10.6 KiB

Last changed by

Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374

History of this file

Take it

1.. currentmodule:: flask23Blueprints and Views4====================56A view function is the code you write to respond to requests to your7application. 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.111213Create a Blueprint14------------------1516A :class:`Blueprint` is a way to organize a group of related views and17other 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.2122Flaskr will have two blueprints, one for authentication functions and23one 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.2627.. code-block:: python28    :caption: ``flaskr/auth.py``2930    import functools3132    from flask import (33        Blueprint, flash, g, redirect, render_template, request, session, url_for34    )35    from werkzeug.security import check_password_hash, generate_password_hash3637    from flaskr.db import get_db3839    bp = Blueprint('auth', __name__, url_prefix='/auth')4041This creates a :class:`Blueprint` named ``'auth'``. Like the application42object, 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.4546Import and register the blueprint from the factory using47:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the48new code at the end of the factory function before returning the app.4950.. code-block:: python51    :caption: ``flaskr/__init__.py``5253    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 = f"User {username} is already registered."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 a 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'))175    def login():176        if request.method == 'POST':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()184185            if user is None:186                error = 'Incorrect username.'187            elif not check_password_hash(user['password'], password):188                error = 'Incorrect password.'189190            if error is None:191                session.clear()192                session['user_id'] = user['id']193                return redirect(url_for('index'))194195            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')251    def logout():252        session.clear()253        return redirect(url_for('index'))254255256Require Authentication in Other Views257-------------------------------------258259Creating, editing, and deleting blog posts will require a user to be260logged in. A *decorator* can be used to check this for each view it's261applied to.262263.. code-block:: python264    :caption: ``flaskr/auth.py``265266    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'))271272            return view(**kwargs)273274        return wrapped_view275276This 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`.