-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.py
115 lines (85 loc) · 2.81 KB
/
blog.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from flask import (
Blueprint, g, request, url_for, render_template, redirect, flash
)
from werkzeug.exceptions import abort
from database import get_db
from auth import login_required
# Blog blueprint
bp = Blueprint('blog', __name__)
@bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
""" Post-create view for creating post and insert
into database and redirect to homepage """
if request.method == 'POST':
title = request.form['title']
body = request.form['body']
db = get_db()
error = None
if not title:
error = 'Title is required'
elif not body:
error = 'Body is required'
if error is None:
db.execute(
'INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)',
[title, body, g.user['id']]
)
db.commit()
return redirect(url_for('blog.index'))
flash(error)
return render_template('blog/create.html')
@bp.route('/')
def index():
""" Index (Homepage) view for showing all posts """
posts = get_db().execute(
'SELECT p.id, title, body, created, author_id, username FROM post p '
'JOIN user u ON author_id = u.id ORDER by created DESC'
).fetchall()
return render_template('blog/index.html', posts=posts)
def get_post(id):
""" Get post for provided id """
post = get_db().execute(
'SELECT title, body, author_id FROM post WHERE id = ?', [id]
).fetchone()
if g.user is None:
abort(403)
elif post is None:
abort(404, 'Post with id:{} doesn\'t exists'.format(id))
elif g.user['id'] != post['author_id']:
abort(401, 'You are not authorized to access the URL requested.')
else:
return post
@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
""" View for updating post and return to
home-page when successful """
post = get_post(id)
if request.method == 'POST':
title = request.form['title']
body = request.form['body']
error = None
db = get_db()
if not title:
error = 'Title is required'
elif not body:
error = 'Body is required'
else:
db.execute(
'UPDATE post SET title = ?, body = ? WHERE id = ?',
[title, body, id]
)
db.commit()
return redirect(url_for('blog.index'))
if error:
flash(error)
return render_template('blog/update.html', post=post)
@bp.route('/delete/<int:id>', methods=['POST'])
@login_required
def delete(id):
""" Function for deleting post """
get_post(id)
db = get_db()
db.execute('DELETE FROM post WHERE id = ?', [id])
db.commit()
return redirect(url_for('blog.index'))