def create_item(data, user_id): """Create a new item, save to database and response it.""" # check if item's title has already existed if ItemModel.query.filter_by(name=data['name'], category_id=data['category_id']).first(): raise BadRequest(f"This category has already had item {data['name']}.") # save item to database and response item = ItemModel(**data, user_id=user_id) item.save_to_db() return jsonify(ItemSchema().dump(item)), 201
def test_item_json(self): with self.app_context(): store = StoreModel('test store') item = ItemModel('test item', 19.99, 1) store.save_to_db() item.save_to_db() item_json = item.json() expected = {'name': 'test item', 'price': 19.99} self.assertDictEqual(expected, item_json)
def new_item(category_id): item_data = request.json if item_data: item_data['category_id'] = category_id item_data['user_id'] = current_identity.id category = CategoryModel.query.get_or_404(category_id) schema = ItemSchema() schema.load(item_data) item = ItemModel(item_data['name'], item_data['description'], item_data['price'], category_id, current_identity.id) item.save_to_db() return jsonify({ 'id': item.id, 'name': item.name, 'description': item.description, 'price': item.price, 'category_id': item.category_id, 'user_id': item.user_id }), 201