Skip to content
Myr

blog.py

This file

Path

examples/tutorial/flaskr/blog.py

125 lines · 3.2 KiB · Python

Last changed by

Not known.

History of this file

Take it

1from flask import Blueprint2from flask import flash3from flask import g4from flask import redirect5from flask import render_template6from flask import request7from flask import url_for8from werkzeug.exceptions import abort910from flaskr.auth import login_required11from flaskr.db import get_db1213bp = Blueprint("blog", __name__)141516@bp.route("/")17def index():18    """Show all the posts, most recent first."""19    db = get_db()20    posts = db.execute(21        "SELECT p.id, title, body, created, author_id, username"22        " FROM post p JOIN user u ON p.author_id = u.id"23        " ORDER BY created DESC"24    ).fetchall()25    return render_template("blog/index.html", posts=posts)262728def get_post(id, check_author=True):29    """Get a post and its author by id.3031    Checks that the id exists and optionally that the current user is32    the author.3334    :param id: id of post to get35    :param check_author: require the current user to be the author36    :return: the post with author information37    :raise 404: if a post with the given id doesn't exist38    :raise 403: if the current user isn't the author39    """40    post = (41        get_db()42        .execute(43            "SELECT p.id, title, body, created, author_id, username"44            " FROM post p JOIN user u ON p.author_id = u.id"45            " WHERE p.id = ?",46            (id,),47        )48        .fetchone()49    )5051    if post is None:52        abort(404, f"Post id {id} doesn't exist.")5354    if check_author and post["author_id"] != g.user["id"]:55        abort(403)5657    return post585960@bp.route("/create", methods=("GET", "POST"))61@login_required62def create():63    """Create a new post for the current user."""64    if request.method == "POST":65        title = request.form["title"]66        body = request.form["body"]67        error = None6869        if not title:70            error = "Title is required."7172        if error is not None:73            flash(error)74        else:75            db = get_db()76            db.execute(77                "INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)",78                (title, body, g.user["id"]),79            )80            db.commit()81            return redirect(url_for("blog.index"))8283    return render_template("blog/create.html")848586@bp.route("/<int:id>/update", methods=("GET", "POST"))87@login_required88def update(id):89    """Update a post if the current user is the author."""90    post = get_post(id)9192    if request.method == "POST":93        title = request.form["title"]94        body = request.form["body"]95        error = None9697        if not title:98            error = "Title is required."99100        if error is not None:101            flash(error)102        else:103            db = get_db()104            db.execute(105                "UPDATE post SET title = ?, body = ? WHERE id = ?", (title, body, id)106            )107            db.commit()108            return redirect(url_for("blog.index"))109110    return render_template("blog/update.html", post=post)111112113@bp.route("/<int:id>/delete", methods=("POST",))114@login_required115def delete(id):116    """Delete a post.117118    Ensures that the post exists and that the logged in user is the119    author of the post.120    """121    get_post(id)122    db = get_db()123    db.execute("DELETE FROM post WHERE id = ?", (id,))124    db.commit()125    return redirect(url_for("blog.index"))