示例#1
0
    def post(self, name):
        # item trying to add is already present in the items list
        if ItemModel.find_by_name(name):
            return {'message': "item '{0}' already exists".format(name)}, 400

        # access class variable by ClassName.variable_name
        request_data = Item.parser.parse_args()
        item = ItemModel(name, request_data['price'], request_data['store_id'])
        try:
            item.upsert_item()
        except:
            return {'message': 'insertion to db failed'}, 500
        # if error then execution will stop at return statement of except block
        # if no error then return the item and success code
        return item.get_json(), 201
示例#2
0
    def put(self, name):
        data = Item.parser.parse_args()
        # check whether item already exists
        try:
            item = ItemModel.find_by_name(name)
        except:
            return {'message': 'db search failed'}, 500

        # if item exists then update it and write it to database,
        # else create a new item and write it to database
        if item:
            item.price = data['price']
        else:
            item = ItemModel(name, data['price'])

        # write the changes to database
        try:
            item.upsert_item()
        except:
            return {'message': 'database write failed'}, 500
        return {"message": 'db write success'}, 200