def insert_item(self): conn = get_connection() cursor = conn.cursor() insert_item_sql = "INSERT INTO items VALUES (%s,%s)" cursor.execute(insert_item_sql, params=(self.name, self.price)) conn.commit() conn.close()
def update_item(self): conn = get_connection() cursor = conn.cursor() update_item_sql = "UPDATE items SET price = %s WHERE name = %s" cursor.execute(update_item_sql, params=(self.price, self.name)) conn.commit() conn.close()
def find_item_by_name(cls, name): conn = get_connection() cursor = conn.cursor() get_item_sql = "SELECT * FROM items where name = %s" cursor.execute(get_item_sql, params=(name, )) data = cursor.fetchone() conn.close() if data: return cls(*data)
def delete(self, name): if ItemModel.find_item_by_name(name): conn = get_connection() cursor = conn.cursor() delete_item_sql = "DELETE FROM items WHERE name = %s" cursor.execute(delete_item_sql, params=(name, )) conn.commit() conn.close() return {'message': 'Item {} deleted'.format(name)}, 200 return {'message': 'Item not found'.format(name)}, 400
def find_by_id(cls, _id): conn = get_connection() cursor = conn.cursor() get_user_sql = 'select * from user where id = %s;' cursor.execute(get_user_sql, params=(_id, )) data = cursor.fetchone() if data: user = cls(*data) else: user = None conn.close() return user
def find_by_username(cls, username): conn = get_connection() cursor = conn.cursor() get_user_sql = "select * from test.user where username=%s" cursor.execute(get_user_sql, params=(username, )) data = cursor.fetchone() if data: user = cls(*data) else: user = None conn.close() return user
def get_items(cls): conn = get_connection() cursor = conn.cursor() get_item_sql = "SELECT * FROM items" cursor.execute(get_item_sql) data = cursor.fetchall() conn.close() items = [] if data: for item in data: items.append({'name': item[0], 'price': item[1]}) return items
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {'message': 'User Exist'}, 400 con = get_connection() cursor = con.cursor() insert_user_sql = "INSERT INTO user VALUES (NULL,%s,%s)" cursor.execute(insert_user_sql, params=(data['username'], data['password'])) con.commit() con.close() return {'message': 'User created Successfully'}, 200