def put(self, id): """ Edit product data """ parser.replace_argument('name', required=False) parser.replace_argument('price', required=False) parser.replace_argument('description', required=False) data = parser.parse_args() item = Product.find_by_id(id) if not item: return {"messages": "User not found"}, 404 name = data.get('name', None) if name and Product.find_by_name(name): return {'message': f'Product {name} already exists'}, 400 for key, value in data.items(): if data[key] is not None: setattr(item, key, value) try: item.save() return { 'payload': { 'product': item.to_json(), } } except Exception as e: return {'message': 'Error while updating the product'}, 500
def get(self, id): """ Return product """ item = Product.find_by_id(id) if item: return {'payload': {'product': item.to_json()}} return {"messages": "Product not found"}, 404
def delete(self, id): """ Delete user """ item = Product.find_by_id(id) if not item: return {"messages": "Product not found"}, 404 try: item.delete() return {"payload": {}, "messages": "Product deleted"} except: return {'message': 'Error while deleting the product'}, 500
def put(self, id): """ Edit sale data """ parser.replace_argument('user_id', help='user_id cannot be blank', required=False) parser.replace_argument('product_id', help='product_id cannot be blank', required=False) data = parser.parse_args() user_id = data.get('user_id') if user_id: if not User.find_by_id(user_id): return {'message': f'User {user_id} doesn\'t exist'}, 400 product_id = data.get('product_id') if product_id: if not Product.find_by_id(product_id): return {'message': f'Product {product_id} doesn\'t exist'}, 400 item = Sale.find_by_id(id) if not item: return {"messages": "Sale not found"}, 404 for key, value in data.items(): if data[key] is not None: setattr(item, key, value) try: item.save() return { 'payload': { 'sale': item.to_json(), } } except Exception as e: return {'message': 'Error while updating the sale'}, 500
def post(self): parser.replace_argument('user_id', help='user_id cannot be blank', required=True) parser.replace_argument('product_id', help='product_id cannot be blank', required=True) data = parser.parse_args() user_id = data.get('user_id') if not User.find_by_id(user_id): return {'message': f'User {user_id} doesn\'t exist'}, 404 product_id = data.get('product_id') if not Product.find_by_id(product_id): return {'message': f'Product {product_id} doesn\'t exist'}, 404 # create new user item = Sale(user_id=data.get('user_id'), product_id=data.get('product_id')) if data.get('date'): item.date = datetime.strptime(data.get('date'), '%Y-%m-%d') if data.get('commission_paid'): item.commission_paid = data.get('commission_paid') try: # Saving user in DB and Generating Access and Refresh token item.save() return { 'payload': { 'sale': item.to_json(), } }, 201 except Exception as e: return {'message': 'Error while saving the sale'}, 500