summaryrefslogtreecommitdiffhomepage
path: root/apioforum/thread.py
blob: 61066a142aff131f8964d2f3fa93fa22f47b5094 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# view posts in thread

from flask import (
    Blueprint, render_template, abort, request, g, redirect,
    url_for, flash
)
from markdown import markdown
from markupsafe import escape
from .db import get_db

bp = Blueprint("thread", __name__, url_prefix="/thread")

@bp.route("/<int:thread_id>")
def view_thread(thread_id):
    db = get_db()
    thread = db.execute("SELECT * FROM threads WHERE id = ?;",(thread_id,)).fetchone()
    if thread is None:
        abort(404)
    else:
        posts = db.execute(
            "SELECT * FROM posts WHERE thread = ? ORDER BY created ASC;",
            (thread_id,)
        ).fetchall()
        rendered_posts = [markdown(escape(q['content'])) for q in posts]
        return render_template("view_thread.html",posts=posts,thread=thread,thread_id=thread_id,rendered_posts=rendered_posts)

@bp.route("/<int:thread_id>/create_post", methods=("POST",))
def create_post(thread_id):
    if g.user is None:
        flash("you need to log in before you can post")
        return redirect(url_for('thread.view_thread',thread_id=thread_id))
    else:
        db = get_db()
        content = request.form['content']
        thread = db.execute("SELECT * FROM threads WHERE id = ?;",(thread_id,)).fetchone()
        if len(content.strip()) == 0:
            flash("you cannot post an empty message")
        elif not thread:
            flash("that thread does not exist")
        else:
            db.execute(
                "INSERT INTO posts (thread,author,content,created) VALUES (?,?,?,current_timestamp);",
                (thread_id,g.user,content)
            )
            db.execute(
                "UPDATE threads SET updated = current_timestamp WHERE id = ?;",
                (thread_id,)
            )
            db.commit()
            flash("post posted postfully")
    return redirect(url_for('thread.view_thread',thread_id=thread_id))

@bp.route("/<int:thread_id>/delete_post/<int:post_id>", methods=["GET","POST"])
def delete_post(thread_id, post_id):
    return f"todo (t: {thread_id}, p: {post_id})"

@bp.route("/<int:thread_id>/edit_post/<int:post_id>",methods=["GET","POST"])
def edit_post(thread_id, post_id):
    if request.method == "GET":
        return render_templace("edit_post.html")