-
Notifications
You must be signed in to change notification settings - Fork 0
/
item.py
97 lines (86 loc) · 3.02 KB
/
item.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
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
import sqlite3
class Item(Resource):
parse = reqparse.RequestParser()
parse.add_argument('price',
type=float,
required=True,
help="This filed can not be blank")
@jwt_required()
def get(self,name):
item = self.find_by_name(name)
if item:
return item
return {'message': "Item not found"}, 404
@classmethod
def find_by_name(cls,name):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "SELECT * from items WHERE name =?"
result = cursor.execute(query, (name,))
row = result.fetchone()
connection.close()
if row:
return {"item": {'name': row[0],'price': row[1]}}
def post(self,name):
if(self.find_by_name(name)):
return {'message': "An item with name {} already exist".format(name)}, 400
data = Item.parse.parse_args()
item ={'name': name, 'price': data['price']}
try:
self.insert(item)
except:
return {"message": "Error occurred while insert "}, 500
return item, 201
@classmethod
def insert(cls,item):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "INSERT INTO items VALUES (?,?)"
cursor.execute(query, (item['name'], item['price']))
connection.commit()
connection.close()
def delete(self,name):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "DELETE FROM items WHERE name=?"
cursor.execute(query, (name,))
connection.commit()
connection.close()
return {'message':'Item deleted'}, 200
def put(self,name):
data= Item.parse.parse_args()
item = self.find_by_name(name)
updated_item = {"name": name, "price": data['price']}
if item is None:
try:
self.insert(updated_item)
except:
return {"message": "Error occurred while insert"}, 500
else:
try:
self.update(updated_item)
except:
return {"message": "Error occurred while update"}, 500
return updated_item
@classmethod
def update(cls,item):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "UPDATE items SET price=? WHERE name=?"
cursor.execute(query, (item['price'],item['name']))
connection.commit()
connection.close()
class ItemsList(Resource):
def get(self):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "SELECT * FROM items"
result = cursor.execute(query)
items =[]
for row in result:
items.append({"name":row[0],"price":row[1]})
connection.commit()
connection.close()
return {'Items': items}, 200