def delete_exercise(id): '''Delete an exercise.''' exercise = get_or_404(Exercise, id) if auth.current_user.id != exercise.author_id: raise AuthorizationError exercise.delete(db.session) return {}, 204
def put_exercise(id): '''Update an exercise.''' exercise = get_or_404(Exercise, id) if auth.current_user.id != exercise.author_id: raise AuthorizationError serializer = Serializer(ExerciseSchema, request.args) exercise.update(db.session, serializer.load(request.get_json())) return serializer.dump(exercise)
def get_user(id): '''Get a single user. ''' if auth.current_user and auth.current_user.id == id: user = auth.current_user serializer = Serializer(ProfileSchema, request.args) else: user = get_or_404(User, id) serializer = Serializer(UserSchema, request.args) return serializer.dump(user)
def post_response(id): '''Post response.''' questionnaire = get_or_404(Questionnaire, id) serializer = Serializer(QuestionnaireResponseSchema, request.args, context=dict(questionnaire=questionnaire)) data = serializer.load(request.get_json()) data.update(dict(user_id=auth.current_user.id, questionnaire_id=id)) response = QuestionnaireResponse.create(db.session, data) db.session.add(response) db.session.commit() return serializer.dump(response)
def put_user(id): '''Update a user.''' user = get_or_404(User, id) if user.id != auth.current_user.id: raise AuthorizationError serializer = Serializer(ProfileSchema, request.args) # This lets the schema validator know about the user to be updated for # validating unique columns. So it can ignore false positives. serializer.context = dict(update_id=user.id) data = serializer.load(request.get_json(), exclude=('password', )) user.update(db.session, data) return serializer.dump(user)
def add_to_favorites(id): '''Add or remove an exercise to favorites.''' if auth.current_user.id != id: raise AuthorizationError data = ActionSchema().load(request.get_json()).data exercise = get_or_404(Exercise, data['id']) if data['action'] == ActionSchema.FAVORITE: auth.current_user.favorite_exercises.append(exercise) else: auth.current_user.favorite_exercises = [ ex for ex in auth.current_user.favorite_exercises if ex.id != data['id'] ] db.session.commit() return {}, 204
def rate_exercise(id): '''Rate an exercise, or update previous rating.''' exercise = get_or_404(Exercise, id) data = Serializer(RatingSchema).load(request.get_json()) rating = Rating.query.filter( Rating.exercise_id == exercise.id, Rating.user_id == auth.current_user.id).\ first() if not rating: # POST is basically a "do what you want" method. So strictly speaking # updating a previous score doesn't violate any rules. rating = Rating(exercise_id=exercise.id, user_id=auth.current_user.id) db.session.add(rating) for key, value in data.iteritems(): setattr(rating, key, value) db.session.commit() return {}, 204