Blog Blueprint

You’ll use the same techniques you learned about when writing the authentication blueprint to write the blog blueprint. The blog should list all posts, allow logged in users to create posts, and allow the author of a post to edit or delete it.

As you implement each view, keep the development server running. As you save your changes, try going to the URL in your browser and testing them out.

The Blueprint

Define the blueprint and register it in the application factory.

flaskr/blog.py

  1. from flask import (
  2. Blueprint, flash, g, redirect, render_template, request, url_for
  3. )
  4. from werkzeug.exceptions import abort
  5. from flaskr.auth import login_required
  6. from flaskr.db import get_db
  7. bp = Blueprint('blog', __name__)

Import and register the blueprint from the factory using app.register_blueprint(). Place the new code at the end of the factory function before returning the app.

flaskr/__init__.py

  1. def create_app():
  2. app = ...
  3. # existing code omitted
  4. from . import blog
  5. app.register_blueprint(blog.bp)
  6. app.add_url_rule('/', endpoint='index')
  7. return app

Unlike the auth blueprint, the blog blueprint does not have a url_prefix. So the index view will be at /, the create view at /create, and so on. The blog is the main feature of Flaskr, so it makes sense that the blog index will be the main index.

However, the endpoint for the index view defined below will be blog.index. Some of the authentication views referred to a plain index endpoint. app.add_url_rule() associates the endpoint name 'index' with the / url so that url_for('index') or url_for('blog.index') will both work, generating the same / URL either way.

In another application you might give the blog blueprint a url_prefix and define a separate index view in the application factory, similar to the hello view. Then the index and blog.index endpoints and URLs would be different.

Index

The index will show all of the posts, most recent first. A JOIN is used so that the author information from the user table is available in the result.

flaskr/blog.py

  1. @bp.route('/')
  2. def index():
  3. db = get_db()
  4. posts = db.execute(
  5. 'SELECT p.id, title, body, created, author_id, username'
  6. ' FROM post p JOIN user u ON p.author_id = u.id'
  7. ' ORDER BY created DESC'
  8. ).fetchall()
  9. return render_template('blog/index.html', posts=posts)

flaskr/templates/blog/index.html

  1. {% extends 'base.html' %}
  2. {% block header %}
  3. <h1>{% block title %}Posts{% endblock %}</h1>
  4. {% if g.user %}
  5. <a class="action" href="{{ url_for('blog.create') }}">New</a>
  6. {% endif %}
  7. {% endblock %}
  8. {% block content %}
  9. {% for post in posts %}
  10. <article class="post">
  11. <header>
  12. <div>
  13. <h1>{{ post['title'] }}</h1>
  14. <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
  15. </div>
  16. {% if g.user['id'] == post['author_id'] %}
  17. <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
  18. {% endif %}
  19. </header>
  20. <p class="body">{{ post['body'] }}</p>
  21. </article>
  22. {% if not loop.last %}
  23. <hr>
  24. {% endif %}
  25. {% endfor %}
  26. {% endblock %}

When a user is logged in, the header block adds a link to the create view. When the user is the author of a post, they’ll see an “Edit” link to the update view for that post. loop.last is a special variable available inside Jinja for loops. It’s used to display a line after each post except the last one, to visually separate them.

Create

The create view works the same as the auth register view. Either the form is displayed, or the posted data is validated and the post is added to the database or an error is shown.

The login_required decorator you wrote earlier is used on the blog views. A user must be logged in to visit these views, otherwise they will be redirected to the login page.

flaskr/blog.py

  1. @bp.route('/create', methods=('GET', 'POST'))
  2. @login_required
  3. def create():
  4. if request.method == 'POST':
  5. title = request.form['title']
  6. body = request.form['body']
  7. error = None
  8. if not title:
  9. error = 'Title is required.'
  10. if error is not None:
  11. flash(error)
  12. else:
  13. db = get_db()
  14. db.execute(
  15. 'INSERT INTO post (title, body, author_id)'
  16. ' VALUES (?, ?, ?)',
  17. (title, body, g.user['id'])
  18. )
  19. db.commit()
  20. return redirect(url_for('blog.index'))
  21. return render_template('blog/create.html')

flaskr/templates/blog/create.html

  1. {% extends 'base.html' %}
  2. {% block header %}
  3. <h1>{% block title %}New Post{% endblock %}</h1>
  4. {% endblock %}
  5. {% block content %}
  6. <form method="post">
  7. <label for="title">Title</label>
  8. <input name="title" id="title" value="{{ request.form['title'] }}" required>
  9. <label for="body">Body</label>
  10. <textarea name="body" id="body">{{ request.form['body'] }}</textarea>
  11. <input type="submit" value="Save">
  12. </form>
  13. {% endblock %}

Update

Both the update and delete views will need to fetch a post by id and check if the author matches the logged in user. To avoid duplicating code, you can write a function to get the post and call it from each view.

flaskr/blog.py

  1. def get_post(id, check_author=True):
  2. post = get_db().execute(
  3. 'SELECT p.id, title, body, created, author_id, username'
  4. ' FROM post p JOIN user u ON p.author_id = u.id'
  5. ' WHERE p.id = ?',
  6. (id,)
  7. ).fetchone()
  8. if post is None:
  9. abort(404, f"Post id {id} doesn't exist.")
  10. if check_author and post['author_id'] != g.user['id']:
  11. abort(403)
  12. return post

abort() will raise a special exception that returns an HTTP status code. It takes an optional message to show with the error, otherwise a default message is used. 404 means “Not Found”, and 403 means “Forbidden”. (401 means “Unauthorized”, but you redirect to the login page instead of returning that status.)

The check_author argument is defined so that the function can be used to get a post without checking the author. This would be useful if you wrote a view to show an individual post on a page, where the user doesn’t matter because they’re not modifying the post.

flaskr/blog.py

  1. @bp.route('/<int:id>/update', methods=('GET', 'POST'))
  2. @login_required
  3. def update(id):
  4. post = get_post(id)
  5. if request.method == 'POST':
  6. title = request.form['title']
  7. body = request.form['body']
  8. error = None
  9. if not title:
  10. error = 'Title is required.'
  11. if error is not None:
  12. flash(error)
  13. else:
  14. db = get_db()
  15. db.execute(
  16. 'UPDATE post SET title = ?, body = ?'
  17. ' WHERE id = ?',
  18. (title, body, id)
  19. )
  20. db.commit()
  21. return redirect(url_for('blog.index'))
  22. return render_template('blog/update.html', post=post)

Unlike the views you’ve written so far, the update function takes an argument, id. That corresponds to the <int:id> in the route. A real URL will look like /1/update. Flask will capture the 1, ensure it’s an int, and pass it as the id argument. If you don’t specify int: and instead do <id>, it will be a string. To generate a URL to the update page, url_for() needs to be passed the id so it knows what to fill in: url_for('blog.update', id=post['id']). This is also in the index.html file above.

The create and update views look very similar. The main difference is that the update view uses a post object and an UPDATE query instead of an INSERT. With some clever refactoring, you could use one view and template for both actions, but for the tutorial it’s clearer to keep them separate.

flaskr/templates/blog/update.html

  1. {% extends 'base.html' %}
  2. {% block header %}
  3. <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>
  4. {% endblock %}
  5. {% block content %}
  6. <form method="post">
  7. <label for="title">Title</label>
  8. <input name="title" id="title"
  9. value="{{ request.form['title'] or post['title'] }}" required>
  10. <label for="body">Body</label>
  11. <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>
  12. <input type="submit" value="Save">
  13. </form>
  14. <hr>
  15. <form action="{{ url_for('blog.delete', id=post['id']) }}" method="post">
  16. <input class="danger" type="submit" value="Delete" onclick="return confirm('Are you sure?');">
  17. </form>
  18. {% endblock %}

This template has two forms. The first posts the edited data to the current page (/<id>/update). The other form contains only a button and specifies an action attribute that posts to the delete view instead. The button uses some JavaScript to show a confirmation dialog before submitting.

The pattern {{ request.form['title'] or post['title'] }} is used to choose what data appears in the form. When the form hasn’t been submitted, the original post data appears, but if invalid form data was posted you want to display that so the user can fix the error, so request.form is used instead. request is another variable that’s automatically available in templates.

Delete

The delete view doesn’t have its own template, the delete button is part of update.html and posts to the /<id>/delete URL. Since there is no template, it will only handle the POST method and then redirect to the index view.

flaskr/blog.py

  1. @bp.route('/<int:id>/delete', methods=('POST',))
  2. @login_required
  3. def delete(id):
  4. get_post(id)
  5. db = get_db()
  6. db.execute('DELETE FROM post WHERE id = ?', (id,))
  7. db.commit()
  8. return redirect(url_for('blog.index'))

Congratulations, you’ve now finished writing your application! Take some time to try out everything in the browser. However, there’s still more to do before the project is complete.

Continue to Make the Project Installable.