Skip to content
Myr

views.rst

This file

Path

docs/tutorial/views.rst

305 lines · 10.7 KiB

Last changed by

Merge pull request #4139 from awijaya22/issue4099David Lordbefore adoption187f6ce

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.'9495            if error is None:96                try:97                    db.execute(98                        "INSERT INTO user (username, password) VALUES (?, ?)",99                        (username, generate_password_hash(password)),100                    )101                    db.commit()102                except db.IntegrityError:103                    error = f"User {username} is already registered."104                else: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#.  If validation succeeds, insert the new user data into the database.129130    -   :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL131        query with ``?`` placeholders for any user input, and a tuple of132        values to replace the placeholders with. The database library133        will take care of escaping the values so you are not vulnerable134        to a *SQL injection attack*.135136    -   For security, passwords should never be stored in the database137        directly. Instead,138        :func:`~werkzeug.security.generate_password_hash` is used to139        securely hash the password, and that hash is stored. Since this140        query modifies data,141        :meth:`db.commit() <sqlite3.Connection.commit>` needs to be142        called afterwards to save the changes.143144    -   An :exc:`sqlite3.IntegrityError` will occur if the username145        already exists, which should be shown to the user as another146        validation error.147148#.  After storing the user, they are redirected to the login page.149    :func:`url_for` generates the URL for the login view based on its150    name. This is preferable to writing the URL directly as it allows151    you to change the URL later without changing all code that links to152    it. :func:`redirect` generates a redirect response to the generated153    URL.154155#.  If validation fails, the error is shown to the user. :func:`flash`156    stores messages that can be retrieved when rendering the template.157158#.  When the user initially navigates to ``auth/register``, or159    there was a validation error, an HTML page with the registration160    form should be shown. :func:`render_template` will render a template161    containing the HTML, which you'll write in the next step of the162    tutorial.163164165Login166-----167168This view follows the same pattern as the ``register`` view above.169170.. code-block:: python171    :caption: ``flaskr/auth.py``172173    @bp.route('/login', methods=('GET', 'POST'))174    def login():175        if request.method == 'POST':176            username = request.form['username']177            password = request.form['password']178            db = get_db()179            error = None180            user = db.execute(181                'SELECT * FROM user WHERE username = ?', (username,)182            ).fetchone()183184            if user is None:185                error = 'Incorrect username.'186            elif not check_password_hash(user['password'], password):187                error = 'Incorrect password.'188189            if error is None:190                session.clear()191                session['user_id'] = user['id']192                return redirect(url_for('index'))193194            flash(error)195196        return render_template('auth/login.html')197198There are a few differences from the ``register`` view:199200#.  The user is queried first and stored in a variable for later use.201202    :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.203    If the query returned no results, it returns ``None``. Later,204    :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list205    of all results.206207#.  :func:`~werkzeug.security.check_password_hash` hashes the submitted208    password in the same way as the stored hash and securely compares209    them. If they match, the password is valid.210211#.  :data:`session` is a :class:`dict` that stores data across requests.212    When validation succeeds, the user's ``id`` is stored in a new213    session. The data is stored in a *cookie* that is sent to the214    browser, and the browser then sends it back with subsequent requests.215    Flask securely *signs* the data so that it can't be tampered with.216217Now that the user's ``id`` is stored in the :data:`session`, it will be218available on subsequent requests. At the beginning of each request, if219a user is logged in their information should be loaded and made220available to other views.221222.. code-block:: python223    :caption: ``flaskr/auth.py``224225    @bp.before_app_request226    def load_logged_in_user():227        user_id = session.get('user_id')228229        if user_id is None:230            g.user = None231        else:232            g.user = get_db().execute(233                'SELECT * FROM user WHERE id = ?', (user_id,)234            ).fetchone()235236:meth:`bp.before_app_request() <Blueprint.before_app_request>` registers237a function that runs before the view function, no matter what URL is238requested. ``load_logged_in_user`` checks if a user id is stored in the239:data:`session` and gets that user's data from the database, storing it240on :data:`g.user <g>`, which lasts for the length of the request. If241there is no user id, or if the id doesn't exist, ``g.user`` will be242``None``.243244245Logout246------247248To log out, you need to remove the user id from the :data:`session`.249Then ``load_logged_in_user`` won't load a user on subsequent requests.250251.. code-block:: python252    :caption: ``flaskr/auth.py``253254    @bp.route('/logout')255    def logout():256        session.clear()257        return redirect(url_for('index'))258259260Require Authentication in Other Views261-------------------------------------262263Creating, editing, and deleting blog posts will require a user to be264logged in. A *decorator* can be used to check this for each view it's265applied to.266267.. code-block:: python268    :caption: ``flaskr/auth.py``269270    def login_required(view):271        @functools.wraps(view)272        def wrapped_view(**kwargs):273            if g.user is None:274                return redirect(url_for('auth.login'))275276            return view(**kwargs)277278        return wrapped_view279280This decorator returns a new view function that wraps the original view281it's applied to. The new function checks if a user is loaded and282redirects to the login page otherwise. If a user is loaded the original283view is called and continues normally. You'll use this decorator when284writing the blog views.285286Endpoints and URLs287------------------288289The :func:`url_for` function generates the URL to a view based on a name290and arguments. The name associated with a view is also called the291*endpoint*, and by default it's the same as the name of the view292function.293294For example, the ``hello()`` view that was added to the app295factory earlier in the tutorial has the name ``'hello'`` and can be296linked to with ``url_for('hello')``. If it took an argument, which297you'll see later, it would be linked to using298``url_for('hello', who='World')``.299300When using a blueprint, the name of the blueprint is prepended to the301name of the function, so the endpoint for the ``login`` function you302wrote above is ``'auth.login'`` because you added it to the ``'auth'``303blueprint.304305Continue to :doc:`templates`.