Skip to content
Myr

blog.rst

This file

Path

docs/tutorial/blog.rst

336 lines · 11.1 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

1.. currentmodule:: flask23Blog Blueprint4==============56You'll use the same techniques you learned about when writing the7authentication blueprint to write the blog blueprint. The blog should8list all posts, allow logged in users to create posts, and allow the9author of a post to edit or delete it.1011As you implement each view, keep the development server running. As you12save your changes, try going to the URL in your browser and testing them13out.1415The Blueprint16-------------1718Define the blueprint and register it in the application factory.1920.. code-block:: python21    :caption: ``flaskr/blog.py``2223    from flask import (24        Blueprint, flash, g, redirect, render_template, request, url_for25    )26    from werkzeug.exceptions import abort2728    from flaskr.auth import login_required29    from flaskr.db import get_db3031    bp = Blueprint('blog', __name__)3233Import and register the blueprint from the factory using34:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the35new code at the end of the factory function before returning the app.3637.. code-block:: python38    :caption: ``flaskr/__init__.py``3940    def create_app():41        app = ...42        # existing code omitted4344        from . import blog45        app.register_blueprint(blog.bp)46        app.add_url_rule('/', endpoint='index')4748        return app495051Unlike the auth blueprint, the blog blueprint does not have a52``url_prefix``. So the ``index`` view will be at ``/``, the ``create``53view at ``/create``, and so on. The blog is the main feature of Flaskr,54so it makes sense that the blog index will be the main index.5556However, the endpoint for the ``index`` view defined below will be57``blog.index``. Some of the authentication views referred to a plain58``index`` endpoint. :meth:`app.add_url_rule() <Flask.add_url_rule>`59associates the endpoint name ``'index'`` with the ``/`` url so that60``url_for('index')`` or ``url_for('blog.index')`` will both work,61generating the same ``/`` URL either way.6263In another application you might give the blog blueprint a64``url_prefix`` and define a separate ``index`` view in the application65factory, similar to the ``hello`` view. Then the ``index`` and66``blog.index`` endpoints and URLs would be different.676869Index70-----7172The index will show all of the posts, most recent first. A ``JOIN`` is73used so that the author information from the ``user`` table is74available in the result.7576.. code-block:: python77    :caption: ``flaskr/blog.py``7879    @bp.route('/')80    def index():81        db = get_db()82        posts = db.execute(83            'SELECT p.id, title, body, created, author_id, username'84            ' FROM post p JOIN user u ON p.author_id = u.id'85            ' ORDER BY created DESC'86        ).fetchall()87        return render_template('blog/index.html', posts=posts)8889.. code-block:: html+jinja90    :caption: ``flaskr/templates/blog/index.html``9192    {% extends 'base.html' %}9394    {% block header %}95      <h1>{% block title %}Posts{% endblock %}</h1>96      {% if g.user %}97        <a class="action" href="{{ url_for('blog.create') }}">New</a>98      {% endif %}99    {% endblock %}100101    {% block content %}102      {% for post in posts %}103        <article class="post">104          <header>105            <div>106              <h1>{{ post['title'] }}</h1>107              <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>108            </div>109            {% if g.user['id'] == post['author_id'] %}110              <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>111            {% endif %}112          </header>113          <p class="body">{{ post['body'] }}</p>114        </article>115        {% if not loop.last %}116          <hr>117        {% endif %}118      {% endfor %}119    {% endblock %}120121When a user is logged in, the ``header`` block adds a link to the122``create`` view. When the user is the author of a post, they'll see an123"Edit" link to the ``update`` view for that post. ``loop.last`` is a124special variable available inside `Jinja for loops`_. It's used to125display a line after each post except the last one, to visually separate126them.127128.. _Jinja for loops: https://jinja.palletsprojects.com/templates/#for129130131Create132------133134The ``create`` view works the same as the auth ``register`` view. Either135the form is displayed, or the posted data is validated and the post is136added to the database or an error is shown.137138The ``login_required`` decorator you wrote earlier is used on the blog139views. A user must be logged in to visit these views, otherwise they140will be redirected to the login page.141142.. code-block:: python143    :caption: ``flaskr/blog.py``144145    @bp.route('/create', methods=('GET', 'POST'))146    @login_required147    def create():148        if request.method == 'POST':149            title = request.form['title']150            body = request.form['body']151            error = None152153            if not title:154                error = 'Title is required.'155156            if error is not None:157                flash(error)158            else:159                db = get_db()160                db.execute(161                    'INSERT INTO post (title, body, author_id)'162                    ' VALUES (?, ?, ?)',163                    (title, body, g.user['id'])164                )165                db.commit()166                return redirect(url_for('blog.index'))167168        return render_template('blog/create.html')169170.. code-block:: html+jinja171    :caption: ``flaskr/templates/blog/create.html``172173    {% extends 'base.html' %}174175    {% block header %}176      <h1>{% block title %}New Post{% endblock %}</h1>177    {% endblock %}178179    {% block content %}180      <form method="post">181        <label for="title">Title</label>182        <input name="title" id="title" value="{{ request.form['title'] }}" required>183        <label for="body">Body</label>184        <textarea name="body" id="body">{{ request.form['body'] }}</textarea>185        <input type="submit" value="Save">186      </form>187    {% endblock %}188189190Update191------192193Both the ``update`` and ``delete`` views will need to fetch a ``post``194by ``id`` and check if the author matches the logged in user. To avoid195duplicating code, you can write a function to get the ``post`` and call196it from each view.197198.. code-block:: python199    :caption: ``flaskr/blog.py``200201    def get_post(id, check_author=True):202        post = get_db().execute(203            'SELECT p.id, title, body, created, author_id, username'204            ' FROM post p JOIN user u ON p.author_id = u.id'205            ' WHERE p.id = ?',206            (id,)207        ).fetchone()208209        if post is None:210            abort(404, f"Post id {id} doesn't exist.")211212        if check_author and post['author_id'] != g.user['id']:213            abort(403)214215        return post216217:func:`abort` will raise a special exception that returns an HTTP status218code. It takes an optional message to show with the error, otherwise a219default message is used. ``404`` means "Not Found", and ``403`` means220"Forbidden". (``401`` means "Unauthorized", but you redirect to the221login page instead of returning that status.)222223The ``check_author`` argument is defined so that the function can be224used to get a ``post`` without checking the author. This would be useful225if you wrote a view to show an individual post on a page, where the user226doesn't matter because they're not modifying the post.227228.. code-block:: python229    :caption: ``flaskr/blog.py``230231    @bp.route('/<int:id>/update', methods=('GET', 'POST'))232    @login_required233    def update(id):234        post = get_post(id)235236        if request.method == 'POST':237            title = request.form['title']238            body = request.form['body']239            error = None240241            if not title:242                error = 'Title is required.'243244            if error is not None:245                flash(error)246            else:247                db = get_db()248                db.execute(249                    'UPDATE post SET title = ?, body = ?'250                    ' WHERE id = ?',251                    (title, body, id)252                )253                db.commit()254                return redirect(url_for('blog.index'))255256        return render_template('blog/update.html', post=post)257258Unlike the views you've written so far, the ``update`` function takes259an argument, ``id``. That corresponds to the ``<int:id>`` in the route.260A real URL will look like ``/1/update``. Flask will capture the ``1``,261ensure it's an :class:`int`, and pass it as the ``id`` argument. If you262don't specify ``int:`` and instead do ``<id>``, it will be a string.263To generate a URL to the update page, :func:`url_for` needs to be passed264the ``id`` so it knows what to fill in:265``url_for('blog.update', id=post['id'])``. This is also in the266``index.html`` file above.267268The ``create`` and ``update`` views look very similar. The main269difference is that the ``update`` view uses a ``post`` object and an270``UPDATE`` query instead of an ``INSERT``. With some clever refactoring,271you could use one view and template for both actions, but for the272tutorial it's clearer to keep them separate.273274.. code-block:: html+jinja275    :caption: ``flaskr/templates/blog/update.html``276277    {% extends 'base.html' %}278279    {% block header %}280      <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>281    {% endblock %}282283    {% block content %}284      <form method="post">285        <label for="title">Title</label>286        <input name="title" id="title"287          value="{{ request.form['title'] or post['title'] }}" required>288        <label for="body">Body</label>289        <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>290        <input type="submit" value="Save">291      </form>292      <hr>293      <form action="{{ url_for('blog.delete', id=post['id']) }}" method="post">294        <input class="danger" type="submit" value="Delete" onclick="return confirm('Are you sure?');">295      </form>296    {% endblock %}297298This template has two forms. The first posts the edited data to the299current page (``/<id>/update``). The other form contains only a button300and specifies an ``action`` attribute that posts to the delete view301instead. The button uses some JavaScript to show a confirmation dialog302before submitting.303304The pattern ``{{ request.form['title'] or post['title'] }}`` is used to305choose what data appears in the form. When the form hasn't been306submitted, the original ``post`` data appears, but if invalid form data307was posted you want to display that so the user can fix the error, so308``request.form`` is used instead. :data:`.request` is another variable309that's automatically available in templates.310311312Delete313------314315The delete view doesn't have its own template, the delete button is part316of ``update.html`` and posts to the ``/<id>/delete`` URL. Since there317is no template, it will only handle the ``POST`` method and then redirect318to the ``index`` view.319320.. code-block:: python321    :caption: ``flaskr/blog.py``322323    @bp.route('/<int:id>/delete', methods=('POST',))324    @login_required325    def delete(id):326        get_post(id)327        db = get_db()328        db.execute('DELETE FROM post WHERE id = ?', (id,))329        db.commit()330        return redirect(url_for('blog.index'))331332Congratulations, you've now finished writing your application! Take some333time to try out everything in the browser. However, there's still more334to do before the project is complete.335336Continue to :doc:`install`.