-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
281 lines (233 loc) · 9.78 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
from flask import (
Flask, request, render_template, session, flash, redirect, url_for, jsonify
)
import string
from db import db_connection
app = Flask(__name__)
app.secret_key = 'THISISMYSECRETKEY' # create the unique one for yourself
@app.route('/login', methods=['GET', 'POST'])
def login():
""" function to show and process login page """
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = db_connection()
cur = conn.cursor()
sql = """
SELECT username
FROM users
WHERE username = '%s' AND password = '%s'
""" % (username, password)
cur.execute(sql)
user = cur.fetchone()
error = ''
if user is None:
error = 'Wrong credentials. No user found'
else:
session.clear()
session['username'] = user[0]
return redirect(url_for('index'))
flash(error)
cur.close()
conn.close()
return render_template('login.html')
@app.route('/register', methods=['GET','POST'])
def register():
if request.method == "POST":
data = request.get_json() or {}
# check if username and password exist :
if data.get('username') and data.get('name') and data.get('password'):
username = data.get('username', '')
name = data.get('name', '')
password = data.get('password', '')
# strip() is to remove excessive whitespaces before saving
username = username.strip()
name = name.strip()
password = password.strip()
conn = db_connection()
cur = conn.cursor()
# insert with the user_id
#AAAAAAAAAAAAAAAAAAAAAAAA COPAS DARI SINI AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
#unique username
if request.method == 'POST':
conn = db_connection()
cur = conn.cursor()
sql = """
SELECT *
FROM users
WHERE username = '%s'
""" % username
cur.execute(sql)
user = cur.fetchone()
error = ''
if user is None:
sql = """
INSERT INTO users (username, name, password) VALUES ('%s', '%s', '%s')
""" % (username, name, password)
cur.execute(sql)
conn.commit() # commit to make sure changes are saved
cur.close()
conn.close()
# an example with redirect
return jsonify({'status': 200, 'message': 'Success'})
else:
return jsonify({'status': 409, 'message': 'User already exist'})
flash(error)
cur.close()
conn.close()
return render_template('register.html')
#AAAAAAAAAAAAAAAAAAAAAAAA COPAS SAMPE SINI AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
# else will be error
return jsonify({'status': 500, 'message': 'No Data submitted'})
return render_template('register.html')
@app.route('/logout')
def logout():
""" function to do logout """
session.clear() # clear all sessions
return redirect(url_for('login'))
@app.route('/')
def index():
conn = db_connection()
cur = conn.cursor()
sql = """
SELECT art.id, art.title, art.body, art.user_name
FROM articles art
JOIN users usr ON usr.username = art.user_name
ORDER BY art.title
"""
cur.execute(sql)
# [(1, "Article Title 1", "Art 1 content"), (2, "Title2", "Content 2"), ...]
articles = cur.fetchall()
cur.close()
conn.close()
return render_template('index.html', articles=articles)
@app.route('/<username>', methods=['GET', 'POST'])
def userpage(username):
# check if user is logged in as $username
# open db connection
conn = db_connection()
cur = conn.cursor()
# sql to select username from database
sql = """
SELECT art.id, art.title, art.body, art.user_name
FROM articles art
WHERE art.user_name = '%s'
ORDER BY art.title
""" % username
cur.execute(sql)
userposts = cur.fetchall()
cur.close()
conn.close()
return render_template('accountpage.html', userposts=userposts)
@app.route('/article/create', methods=['GET', 'POST'])
def create():
# check if user is logged in
if not session:
return redirect(url_for('login'))
if request.method == 'POST':
data = request.get_json() or {}
# check existence of title and body
if data.get('title') and data.get('body'):
title = data.get('title', '')
body = data.get('body', '')
user_name = str(session.get('username'))
# strip() is to remove excessive whitespaces before saving
title = title.strip()
body = body.strip()
conn = db_connection()
cur = conn.cursor()
# insert with the user_id
sql = """
INSERT INTO articles (title, body, user_name) VALUES ('%s', '%s', '%s')
""" % (title, body, user_name)
cur.execute(sql)
conn.commit() # commit to make sure changes are saved
cur.close()
conn.close()
# an example with redirect
return jsonify({'status': 200, 'message': 'Success', 'redirect': '/'})
# else will be error
return jsonify({'status': 500, 'message': 'No Data submitted'})
return render_template('create.html')
@app.route('/<username>/<int:article_id>', methods=['GET'])
def read(username, article_id):
# find the article with id = article_id, return not found page if error
conn = db_connection()
cur = conn.cursor()
sql = """
select art.title, art.body, art.user_name
from articles art
where art.user_name = '%s' and art.id = %d
""" % (username, article_id)
cur.execute(sql)
article = cur.fetchone()
cur.close()
conn.close()
return render_template('detail.html', article=article)
@app.route('/<username>/edit/<int:article_id>', methods=['GET', 'POST'])
def edit(username, article_id):
# check if user is logged in
if not session:
return redirect(url_for('login'))
else :
if username == session['username']:
if request.method == 'POST':
conn = db_connection()
cur = conn.cursor()
title = request.form['title']
body = request.form['body']
title = title.strip()
body = body.strip()
sql_params = (title, body, article_id)
sql = "UPDATE articles SET title = '%s', body = '%s' WHERE id = %s" % sql_params
print(sql)
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
# use redirect to go to certain url. url_for function accepts the
# function name of the URL which is function index() in this case
return redirect(url_for('index'))
else:
return redirect(url_for('index'))
# find the record first
conn = db_connection()
cur = conn.cursor()
sql = 'SELECT id, title, body, user_name FROM articles WHERE id = %s' % article_id
cur.execute(sql)
article = cur.fetchone()
cur.close()
conn.close()
return render_template('edit.html', article=article)
@app.route('/<username>/delete/<int:article_id>', methods=['GET', 'POST'])
def delete(username, article_id):
# check if user is logged in
if not session:
return redirect(url_for('login'))
else:
if username == session['username']:
if request.method == 'POST':
conn = db_connection()
cur = conn.cursor()
sql = """
DELETE FROM articles art WHERE art.id = %d
""" % article_id
print(sql)
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
# use redirect to go to certain url. url_for function accepts the
# function name of the URL which is function index() in this case
return redirect(url_for('index'))
else:
return redirect(url_for('index'))
# find the record first
conn = db_connection()
cur = conn.cursor()
sql = 'SELECT id, title, body, user_name FROM articles art WHERE art.id = %s' % article_id
cur.execute(sql)
article = cur.fetchone()
cur.close()
conn.close()
return render_template('delete.html', article=article)