forked from chinmayips/Ecom-website-with-ChatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
378 lines (338 loc) · 14.2 KB
/
main.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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
from flask import *
import sqlite3, hashlib, os
from werkzeug.utils import secure_filename
import ChatBot
from flask import jsonify, request
#from gevent.wsgi import WSGIServer
app = Flask(__name__)
app.secret_key = 'random string'
UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = set(['jpeg', 'jpg', 'png', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def getLoginDetails():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
if 'email' not in session:
loggedIn = False
firstName = ''
noOfItems = 0
else:
loggedIn = True
cur.execute("SELECT userId, firstName FROM users WHERE email = '" + session['email'] + "'")
userId, firstName = cur.fetchone()
cur.execute("SELECT count(productId) FROM kart WHERE userId = " + str(userId))
noOfItems = cur.fetchone()[0]
conn.close()
return (loggedIn, firstName, noOfItems)
@app.route("/",methods=['POST','GET'])
def root():
bot_resp = ["blank",]
loggedIn, firstName, noOfItems = getLoginDetails()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name,image, price, description, stock FROM products')
itemData = cur.fetchall()
cur.execute('SELECT categoryId, name FROM categories')
categoryData = cur.fetchall()
itemData = parse(itemData)
#return app.response_class(bot_resp)
#return render_template('home.html', bot_resp=bot_resp, itemData=itemData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryData=categoryData)
return render_template('home.html', bot_reply=bot_resp , itemData=itemData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryData=categoryData)
@app.route("/chatbot",methods=['POST','GET'])
def chatbot():
if request.method == 'POST':
usr_req = request.form.get('usr_req')
print("In the Chat bot server function", usr_req)
bot_resp = "Response from server"
#usr_req = request.json.get('usr_req')
print("Data is:" , usr_req)
#for k in data:
# req = data[k]
r = ChatBot.ChatBot()
print("Calling function")
bot_resp = r.Chat_with_Bot(usr_req)
print("Bot resp is:" , bot_resp)
return bot_resp
@app.route("/add")
def admin():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT categoryId, name FROM categories")
categories = cur.fetchall()
conn.close()
return render_template('add.html', categories=categories)
@app.route("/addItem", methods=["GET", "POST"])
def addItem():
if request.method == "POST":
name = request.form['name']
price = float(request.form['price'])
description = request.form['description']
stock = int(request.form['stock'])
categoryId = int(request.form['category'])
#Uploading image procedure
image = request.files['image']
if image and allowed_file(image.filename):
filename = secure_filename(image.filename)
image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
imagename = filename
with sqlite3.connect('database.db') as conn:
try:
cur = conn.cursor()
cur.execute('''INSERT INTO products (name, price, description, image, stock, categoryId) VALUES (?, ?, ?, ?, ?, ?)''', (name, price, description, imagename, stock, categoryId))
conn.commit()
msg="added successfully"
except:
msg="error occured"
conn.rollback()
conn.close()
print(msg)
return redirect(url_for('root'))
@app.route("/remove")
def remove():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name, price, description, image, stock FROM products')
data = cur.fetchall()
conn.close()
return render_template('remove.html', data=data)
@app.route("/removeItem")
def removeItem():
productId = request.args.get('productId')
with sqlite3.connect('database.db') as conn:
try:
cur = conn.cursor()
cur.execute('DELETE FROM products WHERE productID = ' + productId)
conn.commit()
msg = "Deleted successsfully"
except:
conn.rollback()
msg = "Error occured"
conn.close()
print(msg)
return redirect(url_for('root'))
@app.route("/displayCategory")
def displayCategory():
loggedIn, firstName, noOfItems = getLoginDetails()
categoryId = request.args.get("categoryId")
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT products.productId, products.name, products.price, products.image, categories.name FROM products, categories WHERE products.categoryId = categories.categoryId AND categories.categoryId = " + categoryId)
data = cur.fetchall()
conn.close()
categoryName = data[0][4]
data = parse(data)
return render_template('displayCategory.html', data=data, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryName=categoryName)
@app.route("/account/profile")
def profileHome():
if 'email' not in session:
return redirect(url_for('root'))
loggedIn, firstName, noOfItems = getLoginDetails()
return render_template("profileHome.html", loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems)
@app.route("/account/profile/edit")
def editProfile():
if 'email' not in session:
return redirect(url_for('root'))
loggedIn, firstName, noOfItems = getLoginDetails()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT userId, email, firstName, lastName, address1, address2, zipcode, city, state, country, phone FROM users WHERE email = '" + session['email'] + "'")
profileData = cur.fetchone()
conn.close()
return render_template("editProfile.html", profileData=profileData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems)
@app.route("/account/profile/changePassword", methods=["GET", "POST"])
def changePassword():
if 'email' not in session:
return redirect(url_for('loginForm'))
if request.method == "POST":
oldPassword = request.form['oldpassword']
oldPassword = hashlib.md5(oldPassword.encode()).hexdigest()
newPassword = request.form['newpassword']
newPassword = hashlib.md5(newPassword.encode()).hexdigest()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT userId, password FROM users WHERE email = '" + session['email'] + "'")
userId, password = cur.fetchone()
if (password == oldPassword):
try:
cur.execute("UPDATE users SET password = ? WHERE userId = ?", (newPassword, userId))
conn.commit()
msg="Changed successfully"
except:
conn.rollback()
msg = "Failed"
return render_template("changePassword.html", msg=msg)
else:
msg = "Wrong password"
conn.close()
return render_template("changePassword.html", msg=msg)
else:
return render_template("changePassword.html")
@app.route("/updateProfile", methods=["GET", "POST"])
def updateProfile():
if request.method == 'POST':
email = request.form['email']
firstName = request.form['firstName']
lastName = request.form['lastName']
address1 = request.form['address1']
address2 = request.form['address2']
zipcode = request.form['zipcode']
city = request.form['city']
state = request.form['state']
country = request.form['country']
phone = request.form['phone']
with sqlite3.connect('database.db') as con:
try:
cur = con.cursor()
cur.execute('UPDATE users SET firstName = ?, lastName = ?, address1 = ?, address2 = ?, zipcode = ?, city = ?, state = ?, country = ?, phone = ? WHERE email = ?', (firstName, lastName, address1, address2, zipcode, city, state, country, phone, email))
con.commit()
msg = "Saved Successfully"
except:
con.rollback()
msg = "Error occured"
con.close()
return redirect(url_for('editProfile'))
@app.route("/loginForm")
def loginForm():
if 'email' in session:
return redirect(url_for('root'))
else:
return render_template('login.html', error='')
@app.route("/login", methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
if is_valid(email, password):
session['email'] = email
return redirect(url_for('root'))
else:
error = 'Invalid UserId / Password'
return render_template('login.html', error=error)
@app.route("/productDescription")
def productDescription():
loggedIn, firstName, noOfItems = getLoginDetails()
productId = request.args.get('productId')
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name, price, description, image, stock FROM products WHERE productId = ' + productId)
productData = cur.fetchone()
conn.close()
return render_template("productDescription.html", data=productData, loggedIn = loggedIn, firstName = firstName, noOfItems = noOfItems)
@app.route("/addToCart")
def addToCart():
if 'email' not in session:
return redirect(url_for('loginForm'))
else:
productId = int(request.args.get('productId'))
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT userId FROM users WHERE email = '" + session['email'] + "'")
userId = cur.fetchone()[0]
try:
cur.execute("INSERT INTO kart (userId, productId) VALUES (?, ?)", (userId, productId))
conn.commit()
msg = "Added successfully"
except:
conn.rollback()
msg = "Error occured"
conn.close()
return redirect(url_for('root'))
@app.route("/cart")
def cart():
if 'email' not in session:
return redirect(url_for('loginForm'))
loggedIn, firstName, noOfItems = getLoginDetails()
email = session['email']
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT userId FROM users WHERE email = '" + email + "'")
userId = cur.fetchone()[0]
cur.execute("SELECT products.productId, products.name, products.price, products.image FROM products, kart WHERE products.productId = kart.productId AND kart.userId = " + str(userId))
products = cur.fetchall()
totalPrice = 0
for row in products:
totalPrice += row[2]
return render_template("cart.html", products = products, totalPrice=totalPrice, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems)
@app.route("/checkout")
def checkout():
return render_template('checkout.html')
@app.route("/removeFromCart")
def removeFromCart():
if 'email' not in session:
return redirect(url_for('loginForm'))
email = session['email']
productId = int(request.args.get('productId'))
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute("SELECT userId FROM users WHERE email = '" + email + "'")
userId = cur.fetchone()[0]
try:
cur.execute("DELETE FROM kart WHERE userId = " + str(userId) + " AND productId = " + str(productId))
conn.commit()
msg = "removed successfully"
except:
conn.rollback()
msg = "error occured"
conn.close()
return redirect(url_for('root'))
@app.route("/logout")
def logout():
session.pop('email', None)
return redirect(url_for('root'))
def is_valid(email, password):
con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute('SELECT email, password FROM users')
data = cur.fetchall()
for row in data:
if row[0] == email and row[1] == hashlib.md5(password.encode()).hexdigest():
return True
return False
@app.route("/register", methods = ['GET', 'POST'])
def register():
if request.method == 'POST':
#Parse form data
password = request.form['password']
email = request.form['email']
firstName = request.form['firstName']
lastName = request.form['lastName']
address1 = request.form['address1']
address2 = request.form['address2']
zipcode = request.form['zipcode']
city = request.form['city']
state = request.form['state']
country = request.form['country']
phone = request.form['phone']
with sqlite3.connect('database.db') as con:
try:
cur = con.cursor()
cur.execute('INSERT INTO users (password, email, firstName, lastName, address1, address2, zipcode, city, state, country, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (hashlib.md5(password.encode()).hexdigest(), email, firstName, lastName, address1, address2, zipcode, city, state, country, phone))
con.commit()
msg = "Registered Successfully"
except:
con.rollback()
msg = "Error occured"
con.close()
return render_template("login.html", error=msg)
@app.route("/registerationForm")
def registrationForm():
return render_template("register.html")
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def parse(data):
ans = []
i = 0
while i < len(data):
curr = []
for j in range(7):
if i >= len(data):
break
curr.append(data[i])
i += 1
ans.append(curr)
return ans
if __name__ == '__main__':
#http_server = WSGIServer(('', 5000), app)
#http_server.serve_forever()
app.run(debug=True,port=5000,threaded=True)