示例#1
0
文件: api.py 项目: abettadapur/Planr
class PlanResource(Resource):
    def __init__(self):
        self.update_parser = RequestParser()
        self.update_parser.add_argument(
            'name', type=str, required=False, location='json', help='No name provided')
        self.update_parser.add_argument('start_time', type=str, required=False, location='json',
                                        help='No start_time provided')
        self.update_parser.add_argument('end_time', type=str, required=False, location='json',
                                        help='No end_time provided')
        self.update_parser.add_argument('public', type=bool, required=False, location='json',
                                        help='No publicity provided')
        self.plan_repository = PlanRepository()
        super(PlanResource, self).__init__()

    # Get an plan by id
    @authenticate
    def get(self, id, **kwargs):
        user = kwargs['user']
        plan = self.plan_repository.find(id)

        if not plan:
            abort(404, message="No plan with that id exists")

        if plan.user.id != user.id and not query(plan.shared_users).contains(user, lambda lhs, rhs: lhs.id == rhs.id):
            abort(404, message="No plan with that id exists")

        if 'include_polyline' in request.args and request.args['include_polyline']:
            polyline = get_polyline(plan)
            plan_dict = plan.as_dict()
            plan_dict['polylines'] = polyline
            return plan_dict

        return plan

    # Update an plan by id
    @authenticate
    def put(self, id, **kwargs):
        user = kwargs['user']
        args = self.update_parser.parse_args()
        plan = self.plan_repository.find(id)

        if not plan:
            abort(404, message="No plan with that id exists")

        if plan.user.id != user.id:
            permission = self.plan_repository.get_shared_user_permission(
                id, user.id)
            if not permission:
                abort(404, message="No plan with that id exists")
            elif permission == 'READ':
                abort(403, message="This user does not have edit permissions")

        plan.update_from_dict(args)
        result = self.plan_repository.add_or_update(plan)

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

        self.plan_repository.save_changes()
        return plan

    @authenticate
    def delete(self, id, **kwargs):
        user = kwargs['user']
        plan = self.plan_repository.find(id)

        if not plan:
            abort(404, message="No plan with that id exists")

        if plan.user.id != user.id:
            abort(404, message="No plan with that id exists")

        self.plan_repository.delete(id)
        self.plan_repository.save_changes()
        return {"message": "Deleted plan"}