-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
387 lines (311 loc) · 12.7 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
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
379
380
381
382
383
384
385
386
387
from flask import Flask, request, jsonify, make_response ,send_file
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_marshmallow import Marshmallow
from flask.helpers import safe_join
from flask_cors import CORS
from functools import wraps
import jwt
import json
import datetime
import os
import uuid
import base64
import re
from size_recommendation import testing
app = Flask(__name__)
app.config['SECRET_KEY'] = 'myntraHackathon'
CORS(app)
# database name
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# creates SQLALCHEMY object
db = SQLAlchemy(app)
ma = Marshmallow(app)
bcrypt = Bcrypt(app)
def token_required(func):
def wrapper(*args,**kwargs):
token = request.headers['x-auth-token']
if not token:
return jsonify({'message':'Token is missing'})
try:
data = jwt.decode(token,app.config['SECRET_KEY'],algorithms=["HS256"])
request.data = data
except:
return jsonify({'message':'invalid token'})
return func(*args,**kwargs)
wrapper.__name__ = func.__name__
return wrapper
from models import User,user_schema,users_schema,Category,categorys_schema,category_schema,Product,products_schema,product_schema,ProductDetails,Cart,carts_schema,cart_schema
#auth decorator to act as middleware
@app.route("/",methods=["GET"])
def getpost():
return jsonify({'message':"something"})
@app.route("/allUsers",methods=["GET"])
def printAllUsers():
users = User.query.all()
result = users_schema.dump(users)
return jsonify({"users": result})
@app.route("/register",methods=["POST"])
def register():
req = request.json
if(req.get('first_name') and req.get('email') and req.get('password')):
# print(req['email'])
user = User.query.filter_by(email= req['email']).first()
if(user):
return jsonify({'message':'seems like the email id is already registered'})
password = bcrypt.generate_password_hash(req['password']).decode('utf-8')
user1 = User(first_name=req['first_name'],last_name=req['last_name'],email=req['email'],password=password,is_admin = req['is_admin'])
db.session.add(user1)
db.session.commit()
token = jwt.encode({'id':user1.id,'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=180)},app.config['SECRET_KEY'])
# print("token:"+token.decode('UTF-8'))
if token:
resp = {
'token': token,
'user' : {
'first_name': user1.first_name,
'last_name' : user1.last_name,
'email': user1.email,
'id' : user1.id
}
}
return jsonify(resp)
else:
return jsonify({'message':'Problem in creating a token'})
else:
return jsonify({'message': 'please enter all the values required for the creation of a new user'})
@app.route("/login",methods=["POST"])
def login():
req = request.json
if(req.get('email') and req.get('password')):
user = User.query.filter_by(email= req['email']).first()
if(user):
if(user and bcrypt.check_password_hash(user.password,req['password'])):
#things to do after checking the email and password
token = jwt.encode({'id':user.id,'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=180)},app.config['SECRET_KEY'])
# print("token:"+token.decode('UTF-8'))
if token:
resp = {
'token': token,
'user' : user_schema.dump(user)
}
return jsonify(resp)
else:
return jsonify({'message':'Problem in creating a token'})
else:
return jsonify({'message':'it seems that this email is not registered'})
else:
return jsonify({'message':'Login Unsuccesful.Please check email and password'})
@app.route('/login/user',methods=['GET'])
@token_required
def protected():
data = request.data
print(data)
user = User.query.get(data['id'])
if user:
resp ={
'first_name': user.first_name,
'last_name' : user.last_name,
'email':user.email,
"id":user.id
}
return jsonify(resp)
else:
return jsonify({'message':'This is a protected'})
@app.route('/category/new',methods=['POST'])
@token_required
def createNewCategory():
# try:
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
body = request.json
if not body.get('name'):
return jsonify({'message' : 'please provide all the essential info'})
newCategory = Category(name=body['name'],description=body['description'])
if not newCategory:
return jsonify({'message':'Could not create the new category'})
db.session.add(newCategory)
db.session.commit()
rep = {
'name' : newCategory.name,
'id':newCategory.id,
'description':newCategory.description
}
return jsonify(rep)
# except :
# return jsonify({'message':'Could not create the new category'})
@app.route("/category/all",methods=["GET"])
def printAllCategories():
categories = Category.query.all()
result = categorys_schema.dump(categories)
return jsonify({"categories": result})
@app.route('/category/<int:category_id>/update',methods=['POST'])
@token_required
def updateCategory(category_id):
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
data = request.json
category = Category.query.get(category_id)
if data['name'] :
category.name = data['name']
if data['description'] :
category.description = data['description']
db.session.commit()
return jsonify(category_schema.dump(category))
@app.route('/category/<int:category_id>/delete',methods=['POST'])
@token_required
def deleteCategory(category_id):
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
data = request.json
category= Category.query.get_or_404(category_id)
db.session.delete(category)
db.session.commit()
return jsonify({'message' : 'Category deleted succesfully'})
#routes for crud application of Product
@app.route('/product/new',methods=['POST'])
@token_required
def createNewProduct():
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
data = request.json
category = Category.query.filter_by(name= data['category_name']).first()
if not category:
return jsonify({'message' : 'Please enter a valid category'})
newProduct = Product(product_name=data['product_name'],description=data['description'],brand=data['brand'],discount=data['discount'],regular_price=data['regular_price'],category_id=category.id,image=data['image'])
db.session.add(newProduct)
db.session.commit()
if(data['details']):
print('gonna start entering the product details')
for detail in data['details']:
prod_details = ProductDetails(product_id=newProduct.id,size=detail['size'],quantity=detail['quantity'])
db.session.add(prod_details)
db.session.commit()
return jsonify(product_schema.dump(newProduct))
@app.route('/product/all',methods=['GET'])
@token_required
def getAllProduct():
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
products = Product.query.all()
result = products_schema.dump(products)
return jsonify(result)
@app.route('/product/<int:product_id>/delete',methods=['POST'])
@token_required
def deleteProduct(product_id):
user = User.query.get(request.data['id'])
if not user.is_admin :
return jsonify({'message' : 'only a admin can access this route'})
product= Product.query.get_or_404(product_id)
db.session.delete(product)
details= ProductDetails.query.filter_by(product_id = product_id ).all()
for detail in details:
db.session.delete(details)
db.session.commit()
return jsonify({'message' : 'The product was deleted succesfully'})
@app.route('/category/<int:category_id>/products',methods=['GET'])
def categoryProducts(category_id):
category = Category.query.get(category_id)
result = category_schema.dump(category)
# print(result)
return jsonify(result)
@app.route('/category/<int:category_id>/product/<int:product_id>',methods=['GET'])
def getProduct(category_id,product_id):
category = Category.query.get(category_id)
if not category:
return jsonify({'message':'no such category'})
category_result = category_schema.dump(category)
product = Product.query.get(product_id)
if not product:
return jsonify({'message':'no such product with this product id'})
product_result = product_schema.dump(product)
return jsonify({'category' : category_result,'product' : product_result})
@app.route('/cartitems',methods=['GET'])
@token_required
def userCartItem():
user = User.query.get(request.data['id'])
productsInCart = Cart.query.filter_by(user_id=user.id).all()
result = carts_schema.dump(productsInCart)
return jsonify(result)
@app.route('/addtocart',methods=['POST'])
@token_required
def addToCart():
user = User.query.get(request.data['id'])
data = request.json
newProductInCart = Cart(user_id=user.id,product_id=data['product_id'],product_details_id=data['product_details_id'],quantity=data['quantity'])
db.session.add(newProductInCart)
db.session.commit()
return jsonify({'message' : 'item has been added to the cart'})
@app.route('/cartitems/<int:cart_id>/delete',methods=['POST'])
@token_required
def deletefromCart(cart_id):
user = User.query.get(request.data['id'])
cartProductsToBeDeleted = Cart.query.get(cart_id)
db.session.delete(cartProductsToBeDeleted)
db.session.commit()
return jsonify({'message' : 'The product has been deleted from the users cart '})
@app.route('/cartitems/<int:cart_id>/update',methods=['POST'])
@token_required
def UpdateCart(cart_id):
user = User.query.get(request.data['id'])
data = request.json
cartProductsToBeDeleted = Cart.query.get(cart_id)
if data['quantity']:
cartProductsToBeDeleted.quantity = data['quantity']
db.session.commit()
return jsonify(cart_schema.dumps(cartProductsToBeDeleted))
@app.route('/tryiton/product/<int:product_id>',methods=['POST'])
def tryItOn(product_id):
data = request.json
product = Product.query.get(product_id)
imgdata = base64.b64decode(re.sub("data:image/jpeg;base64,", '', str(data['image'])))
random_id = uuid.uuid4()
filename = 'uploads/' + str(random_id) + ".jpg" # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
# recommendedProd = _______
return jsonify({'message':'successful'})
@app.route('/upload/<filename>',methods=['GET'])
def hostFiles(filename):
# filename = safe_join(app.root_path,"some_image")
print(filename)
return send_file(os.getcwd() + '/uploads' +'/' + filename)
@app.route('/testing',methods=['GET'])
@token_required
def xyz():
data = request.data
user = User.query.get(data['id'])
recomSize = testing(user.chest,user.frontal,user.shoulder)
return jsonify({'recommendedSize' : recomSize})
@app.route('/storeSize',methods=['POST'])
@token_required
def storeSize():
req = request.json
data = request.data
user = User.query.get(data['id'])
if(req.get('chest') and req.get('frontal') and req.get('shoulder')) :
user.chest = req.get('chest')
user.frontal = req.get('frontal')
user.shoulder = req.get('shoulder')
db.session.commit()
result = user_schema.dump(user)
return jsonify({'user' : result})
else:
return jsonify({'message' : 'Please fill all the required fields'})
@app.route('/fileUpload',methods=['POST'])
def storeUploadedFile():
file = request.files['image']
file.save(dst='uploads/example.jpg', buffer_size=16384)
return jsonify({'message' : "file upload is done"})
# @app.route('/skinTone',methods=['GET'])
# @token_required
def getApp():
return app
if __name__ == "__main__":
app.run(debug=True)