-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
354 lines (292 loc) · 12 KB
/
app.py
File metadata and controls
354 lines (292 loc) · 12 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
from flask import Flask, render_template, url_for, redirect, request, session, flash
from flask_socketio import SocketIO, emit
from pymongo import MongoClient
from bson.objectid import ObjectId
import functools
import bcrypt
import os
from os.path import join, dirname, realpath
from werkzeug.utils import secure_filename
from datetime import datetime
client = MongoClient("mongodb://sejongweb:SoobakMarket%40@vkv.kr:27010/")
db = client["webapp"]
products_col = db.products
user_col = db.user
category_col = db.category
local_col = db.local
messages_collection = db['messages']
rooms_collection = db['rooms']
app = Flask(__name__)
socketio = SocketIO(app)
# settings for uploading files feature
PATH_UPLOAD = 'static/uploads'
FULL_UPLOAD_FOLDER = join(dirname(realpath(__file__)), PATH_UPLOAD) #path for uploaded files
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# set the config for upload folder
app.config['UPLOAD_FOLDER'] = FULL_UPLOAD_FOLDER
app.secret_key = 'w42yhpl7qu6qkwmearybxe3vx9cy1m2yzv8apcd7hq0zwqzc5iufjt2ca2v66hlj'
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
userid = session.get('userid')
if userid is None:
return redirect(url_for('login'))
return view(**kwargs)
return wrapped_view
# function to check that file extention is allowed to be uploaded
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# this function will return filename
def upload_image_file(file):
# if the file type/extention is allowed then upload the fil
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
# rename the file and add the datetime now in front of the filename
generated_datetime = datetime.now().strftime('%Y%m%d%H%M%S%f')
filename = generated_datetime+"_"+filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return filename
else:
# if the file type is not allowed
flash('Allowed image types are -> png, jpg, jpeg, gif')
return ""
@app.route('/')
def index():
product_data = products_col.find({}).sort("_id", -1)
product_data_list = list(product_data)
return render_template("home.html", products=product_data_list)
@app.route('/upload')
@login_required
def upload():
return render_template("upload.html")
@app.route('/upload/new', methods=['GET', 'POST'])
@login_required
def new_product():
if request.method == 'POST':
file = request.files['image']
title = request.form['title'].strip()
seller = session['userid']
content = request.form['content'].strip()
local = int(request.form['local'].strip())
price = int(request.form['price'].strip())
category = int(request.form['Uploadcategory'].strip())
view_num = 0
chat_num = 0
heart_num = 0
new_data = { "title": title, "seller": seller, "content": content, "created_date": datetime.now(), "local": local, "category": category, "price":price, "view_num":view_num, "chat_num":chat_num, "heart_num":heart_num}
if file.filename != '':
image_filename = upload_image_file(file)
if image_filename:
new_data["image"] = image_filename
products_col.insert_one(new_data)
flash("Upload Success")
return redirect(url_for('index'))
return redirect(url_for('upload'))
@app.route('/display/<filename>')
def display_image(filename):
return redirect(url_for('static', filename='uploads/' + filename), code=301)
@app.route('/product/<id>')
def product_detail(id):
product_data = ""
try:
_id_converted = ObjectId(id)
search_filter = {"_id": _id_converted}
product_data = products_col.find_one(search_filter)
except:
print("ID is not found/invalid")
view_num = int(product_data["view_num"])
updatedvalues = {"view_num":view_num+1}
update_view_data(_id_converted, updatedvalues)
category_data = category_col.find_one({"num":product_data['category']})
local_data = local_col.find_one({"num":product_data['local']})
return render_template("product_detail.html", data=product_data, category = category_data, local=local_data)
def update_view_data(_id_converted, updatedvalues):
query_by_id = {"_id": _id_converted}
new_updated_value = { "$set": updatedvalues }
products_col.update_one(query_by_id, new_updated_value)
@app.route('/category/<id>')
def category(id):
product_data = products_col.find({"category": int(id)}).sort("_id",-1)
category_data = category_col.find_one({"num": int(id)})
if(int(id)==0):
product_data = products_col.find({}).sort("_id",-1)
category_data['name'] = "전체 제품"
local_data = local_col.find({}).sort("num",1)
local_data_list = list(local_data)
product_data_list = list(product_data)
return render_template("category.html", products=product_data_list, local = local_data_list, category = category_data)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "POST":
userid = request.form['userid'].strip()
password = request.form['password'].strip()
user_data = user_col.find_one({"userid": userid})
if user_data:
user_data_password = user_data['password']
if bcrypt.checkpw(password.encode('utf-8'), user_data_password):
session["userid"] = userid
return redirect(url_for('index'))
else:
flash('User ID or Password is Invalid. Please Try Again.')
return redirect(url_for('login'))
else:
flash('User ID or Password is Invalid. Please Try Again.')
return redirect(url_for('login'))
userid = session.get('userid')
if userid:
return redirect(url_for('index'))
return render_template("login.html")
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == "POST":
userid = request.form['userid'].strip()
password = request.form['password'].strip()
nickname = request.form['nickname'].strip()
today = datetime.now()
year = str(today.year)
month = str(today.month)
day = str(today.day)
created_date = year + '-' + month + '-' + day
user_data1 = user_col.find_one({"userid": userid})
user_data2 = user_col.find_one({"nickname": nickname})
if user_data1:
flash('User ID Already Exist.')
return redirect(url_for('register'))
elif user_data2:
flash('Nickname Already Exist.')
return redirect(url_for('register'))
else:
password_encrypted = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
user_col.insert_one({
"userid": userid,
"password": password_encrypted,
"nickname": nickname,
"created_date": created_date
})
return redirect(url_for('index'))
userid = session.get('userid')
if userid:
return redirect(url_for('index'))
return render_template("register.html")
@app.route('/logout')
@login_required
def logout():
session.clear()
return redirect(url_for('index'))
@app.route('/mypage')
@login_required
def mypage():
userid = session.get('userid')
userinformation = user_col.find_one({"userid": userid})
nickname = userinformation['nickname']
created_date = userinformation['created_date']
product_data = products_col.find({"seller": userid}).sort("_id", -1)
product_data_list = list(product_data)
return render_template("mypage.html", products=product_data_list, userid=userid, nick=nickname, date=created_date)
#delete
@app.route('/product/delete/<id>', methods=['POST'])
@login_required
def product_delete(id):
if request.method == "POST":
_id_converted = ObjectId(id)
query_by_id = {"_id": _id_converted}
products_col.delete_one(query_by_id)
flash("The data has been successfully deleted.")
return redirect(url_for('index'))
@app.route('/update_product/<id>', methods=['GET', 'POST'])
@login_required
def update_product(id):
if request.method == 'POST':
_id = request.form['_id'].strip()
file = request.files['image']
title = request.form['title'].strip()
seller = session['userid']
content = request.form['content'].strip()
local = int(request.form['local'].strip())
price = int(request.form['price'].strip())
category = int(request.form['Uploadcategory'].strip())
updatedvalues = { "title": title, "seller": seller, "content": content, "local": local, "price": price, "category": category}
if file.filename != '':
image_filename = upload_image_file(file)
if image_filename:
updatedvalues["image"] = image_filename
update_post_data(_id, updatedvalues)
flash("The data has been successfully updated.")
return redirect(url_for('product_detail', id=_id))
data = ""
try:
_id_converted = ObjectId(id)
search_filter = {"_id": _id_converted}
data = products_col.find_one(search_filter)
except:
print("ID is not found/invalid")
return render_template("update.html", data=data)
def update_post_data(_id, updatedvalues):
_id_converted = ObjectId(_id)
query_by_id = {"_id": _id_converted}
new_updated_value = { "$set": updatedvalues }
products_col.update_one(query_by_id, new_updated_value)
#search
@app.route('/search_product', methods=['POST'])
def search_product():
if request.method == "POST":
search_word = request.form['search_word'].strip()
myquery = {
"title": {
"$regex": search_word,
"$options" :'i' # case-insensitive
}
}
all_products = products_col.find(myquery).sort("_id", -1)
product_data_list = list(all_products)
return render_template("search_product.html", products=product_data_list, word=search_word)
@app.route('/rooms')
def rooms():
username = session.get('userid')
if not username:
return redirect('/login')
my_rooms = rooms_collection.find({'$or': [{'user1': username}, {'user2': username}]})
return render_template('rooms.html', username=username, rooms=my_rooms)
@app.route('/create_room', methods=['POST'])
def create_room():
username = session.get('userid')
if not username:
return redirect('/login')
user1 = username
user2 = request.form['user2']
room = rooms_collection.find_one({'user1': user1, 'user2': user2})
if not room:
room = {'user1': user1, 'user2': user2}
rooms_collection.insert_one(room)
room = rooms_collection.find_one({'user1': user1, 'user2': user2})
return redirect('/chat/'+str(room['_id']))
@app.route('/chat/<room_id>')
def chat(room_id):
username = session.get('userid')
if not username:
return redirect('/')
room = rooms_collection.find_one({'_id': ObjectId(room_id)})
if not room or (room['user1'] != username and room['user2'] != username):
return redirect('/rooms')
messages = messages_collection.find({'room_id': room_id}).sort('_id', 1)
return render_template('chat.html', username=username, room=room, messages=messages)
@socketio.on('send_message')
def handle_send_message(data):
# Handle the received message data
message = data['message']
room_id = data['room_id']
username = session.get('userid')
# Save the message to the database
messages_collection.insert_one({
'message': message,
'room_id': room_id,
'username': username
})
# Broadcast the message to all connected clients
emit('receive_message', {
'message': message,
'room_id': room_id,
'username': username
}, room_id=room_id, broadcast=True)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', debug=True, port=2023)