-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (66 loc) · 2.41 KB
/
app.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
from flask import Flask, render_template, request, redirect, url_for
import mysql.connector
app = Flask(__name__)
def get_db_connection():
connection = mysql.connector.connect(
host='localhost',
user='root',
password='Reabetsweneo03#',
database='blog'
)
return connection
@app.route('/')
def index():
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM comments ORDER BY created_at DESC')
comments = cursor.fetchall()
cursor.close()
connection.close()
return render_template('index.html', comments=comments)
@app.route('/submit_comment', methods=['POST'])
def submit_comment():
if request.method == 'POST':
name = request.form.get('name')
comment = request.form.get('comment')
post_id = request.form.get('post_id')
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('INSERT INTO comments (name, comment, post_id) VALUES (%s, %s, %s)',
(name, comment, post_id))
connection.commit()
cursor.close()
connection.close()
return redirect('/')
@app.route('/edit_comment/<int:id>', methods=['GET'])
def edit_comment(id):
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute('SELECT * FROM comments WHERE id = %s', (id,))
comment = cursor.fetchone()
cursor.close()
connection.close()
return render_template('edit_comment.html', comment=comment)
@app.route('/update_comment/<int:id>', methods=['POST'])
def update_comment(id):
name = request.form.get('name')
comment = request.form.get('comment')
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('UPDATE comments SET name = %s, comment = %s WHERE id = %s',
(name, comment, id))
connection.commit()
cursor.close()
connection.close()
return redirect('/')
@app.route('/delete_comment/<int:id>', methods=['GET'])
def delete_comment(id):
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute('DELETE FROM comments WHERE id = %s', (id,))
connection.commit()
cursor.close()
connection.close()
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)