示例#1
0
文件: api.py 项目: abettadapur/Planr
class ItemResource(Resource):
    def __init__(self):
        self.plan_repository = PlanRepository()
        self.item_repository = ItemRepository()
        self.category_repository = YelpCategoryRepository()
        super(ItemResource, self).__init__()

    @authenticate
    def get(self, plan_id, item_id, **kwargs):
        user = kwargs['user']
        plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")
        item = query(plan.items).where(lambda i: i.id ==
                                                 item_id).single_or_default(default=None)
        if not item:
            abort(404, message="This item does not exist")
        return item

    @authenticate
    def put(self, plan_id, item_id, **kwargs):
        user = kwargs['user']
        json = request.json
        new_item = Item.from_json(json)

        if new_item.id != item_id:
            on_error(error_message="Could not update item, ids do not match")

        plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")

        old_item = query(plan.items).where(lambda i: i.id ==
                                                 item_id).single_or_default(default=None)
        if not old_item:
            abort(404, message="This item does not exist")

        result = self.item_repository.add_or_update(new_item)

        if not result.success():
            on_error(error_message="Could not update item", result=result)

        self.item_repository.save_changes()
        return new_item

    @authenticate
    def delete(self, plan_id, item_id, **kwargs):
        user = kwargs['user']
        plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")

        item = query(plan.items).where(lambda i: i.id ==
                                                 item_id).single_or_default(default=None)
        if not item:
            abort(404, message="This item does not exist")

        plan.remove_item(item)
        self.item_repository.delete(id)
        self.item_repository.save_changes()
        return {"message": "Deleted item"}
示例#2
0
    def clear_plan(self, plan):
        item_repository = ItemRepository()
        for item in plan.items:
            item_repository.delete(item.id)

        item_repository.save_changes()