コード例 #1
0
ファイル: exercises.py プロジェクト: Kareeeeem/AMC
def post_exercises():
    '''Post new exercise.'''
    serializer = Serializer(ExerciseSchema, request.args)
    data = dict(author_id=auth.current_user.id,
                **serializer.load(request.get_json()))
    exercise = Exercise.create(db.session, data)
    rv = serializer.dump(exercise)
    return rv, 201, get_location_header('.get_exercise', id=exercise.id)
コード例 #2
0
ファイル: exercises.py プロジェクト: Kareeeeem/AMC
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)
コード例 #3
0
def get_responses(id):
    '''Get responses.'''
    serializer = Serializer(QuestionnaireResponseSchema, request.args)
    query = QuestionnaireResponse.query.\
        filter(QuestionnaireResponse.user_id == auth.current_user.id).\
        filter(QuestionnaireResponse.questionnaire_id == id).\
        order_by(QuestionnaireResponse.created_at.desc())
    page = Pagination(request, query=query)
    return serializer.dump_page(page)
コード例 #4
0
ファイル: users.py プロジェクト: Kareeeeem/AMC
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)
コード例 #5
0
ファイル: users.py プロジェクト: Kareeeeem/AMC
def post_users():
    '''Register a user.'''
    serializer = Serializer(ProfileSchema, request.args)
    user = User.create(db.session,
                       serializer.load(request.get_json()),
                       commit=False)
    default_exercises = Exercise.query.filter(Exercise.default).all()
    user.favorite_exercises = default_exercises
    db.session.commit()
    rv = serializer.dump(user)
    return rv, 201, get_location_header('.get_user', id=user.id)
コード例 #6
0
def get_questionnaires():
    '''Get questionnaires.'''
    serializer = Serializer(QuestionnaireSchema, request.args)
    query = Questionnaire.query.\
        outerjoin(QuestionnaireResponse, and_(
            QuestionnaireResponse.user_id == auth.current_user.id,
            QuestionnaireResponse.questionnaire_id == Questionnaire.id
        )).\
        options(contains_eager(Questionnaire.responses))

    page = Pagination(request, query=query)
    return serializer.dump_page(page)
コード例 #7
0
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)
コード例 #8
0
ファイル: users.py プロジェクト: Kareeeeem/AMC
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)
コード例 #9
0
def get_questionnaire(id):
    '''Get questionnaire.'''

    questionnaire = Questionnaire.query.\
        outerjoin(QuestionnaireResponse, and_(
            QuestionnaireResponse.user_id == auth.current_user.id,
            QuestionnaireResponse.questionnaire_id == Questionnaire.id
        )).\
        filter(Questionnaire.id == id).\
        options(contains_eager(Questionnaire.responses)).first()

    if not questionnaire:
        abort(404)

    serializer = Serializer(QuestionnaireSchema, request.args)
    return serializer.dump(questionnaire)
コード例 #10
0
ファイル: exercises.py プロジェクト: Kareeeeem/AMC
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
コード例 #11
0
ファイル: exercises.py プロジェクト: Kareeeeem/AMC
def get_exercise(id):
    '''Get an exercise.'''
    query = Exercise.query.filter(Exercise.id == id)

    if auth.current_user:
        result = query.add_entity(Rating).\
            join(Rating).\
            filter(Rating.user_id == auth.current_user.id).\
            first()

        try:
            exercise = setattr_and_return(result[0], 'user_rating', result[1])
        except TypeError:
            exercise = None
    else:
        exercise = query.first()

    if not exercise:
        abort(404)

    serializer = Serializer(ExerciseSchema, request.args)
    return serializer.dump(exercise)
コード例 #12
0
ファイル: test_pagination.py プロジェクト: Kareeeeem/AMC
def test_many_pages(session):
    users = [
        User(username='******' % i,
             email='*****@*****.**' % i,
             password='******') for i in xrange(10)
    ]
    session.add_all(users)
    session.commit()
    query = User.query
    request = FakeRequest(args={'per_page': 2})
    page = Pagination(request, query)
    result = Serializer(UserSchema).dump_page(page)
    assert len(result['items']) == 2
コード例 #13
0
ファイル: users.py プロジェクト: Kareeeeem/AMC
def get_profile():
    '''Get a single user. '''
    return Serializer(ProfileSchema, request.args).dump(auth.current_user)
コード例 #14
0
ファイル: users.py プロジェクト: Kareeeeem/AMC
def get_users():
    '''Get users.'''
    serializer = Serializer(UserSchema, request.args)
    query = User.query
    page = Pagination(request, query=query)
    return serializer.dump_page(page)
コード例 #15
0
ファイル: exercises.py プロジェクト: Kareeeeem/AMC
def get_exercises(favorited_by=None):
    '''Get exercise collection, if favorited_by is set then get the
    collection of favorites of the user.'''

    user_id = auth.current_user.id if auth.current_user else None

    # client requests favorites that are not his.
    if favorited_by and favorited_by != user_id:
        raise AuthorizationError

    search = request.args.get('search')
    category = request.args.get('category')
    order_by = request.args.get('order_by')
    author = request.args.get('author')

    orderfunc = desc
    if order_by and len(order_by) > 0 and order_by[-1] in '+ -'.split():
        if order_by[-1] == '+':
            orderfunc = asc
        order_by = order_by[:-1]

    query = Exercise.query

    if search:
        search_terms = (' | ').join(search.split())
        query = query.add_columns(func.ts_rank(
            Exercise.tsv, func.to_tsquery(search_terms)).label('search_rank')).\
            filter(Exercise.tsv.match(search_terms))

        if order_by == 'relevance':
            query = query.order_by(nullslast(orderfunc('search_rank')))

    if user_id:
        user_rating = aliased(Rating, name='user_rating')

        query = query.add_entity(user_rating).\
            outerjoin(user_rating, and_(user_rating.exercise_id == Exercise.id,
                                        user_rating.user_id == user_id))

        if order_by == 'user_rating':
            query = query.order_by(nullslast(orderfunc(user_rating.rating)))
        elif order_by == 'user_fun_rating':
            query = query.order_by(nullslast(orderfunc(user_rating.fun)))
        elif order_by == 'user_effective_rating':
            query = query.order_by(nullslast(orderfunc(user_rating.effective)))
        elif order_by == 'user_clear_rating':
            query = query.order_by(nullslast(orderfunc(user_rating.clear)))

        # when if favorited_by is not None then we only want the user favorites
        # and isouter will be set to False. Meaning we will do an inner join If
        # favorited_by is None then isouter will be True and we will do an
        # outer join meaning we want to know which exercises the user favorited
        # but we want all of them.
        isouter = not bool(favorited_by)

        # include a column from the UserFavoriteExercise table or `0`.
        # this will get serialized as a Boolean to signify favorited or not.
        query = query.\
            add_columns(func.coalesce(UserFavoriteExercise.exercise_id, 0).label('favorited')).\
            join(UserFavoriteExercise,
                 and_(UserFavoriteExercise.exercise_id == Exercise.id,
                      UserFavoriteExercise.user_id == user_id),
                 isouter=isouter)

    if author:
        query = query.join(
            User, and_(User.id == Exercise.author_id, User.username == author))

    if category:
        category = parse_query_params(request.args, key='category')
        query = query.join(Category).filter(Category.name.in_(category))

    if 'author' in parse_query_params(request.args, key='expand'):
        query = query.options(joinedload(Exercise.author))

    if order_by in ['average_rating', 'rating']:
        query = query.order_by(nullslast(orderfunc(Exercise.avg_rating)))
    elif order_by == 'average_fun_rating':
        query = query.order_by(nullslast(orderfunc(Exercise.avg_fun_rating)))
    elif order_by == 'average_clear_rating':
        query = query.order_by(nullslast(orderfunc(Exercise.avg_clear_rating)))
    elif order_by == 'average_effective_rating':
        query = query.order_by(
            nullslast(orderfunc(Exercise.avg_effective_rating)))
    elif order_by == 'popularity':
        query = query.order_by(nullslast(orderfunc(Exercise.popularity)))
    elif order_by == 'updated_at':
        query = query.order_by(orderfunc(Exercise.updated_at))
    else:
        query = query.order_by(orderfunc(Exercise.created_at))

    page = Pagination(request, query=query)
    return Serializer(ExerciseSchema, request.args).dump_page(page)
コード例 #16
0
ファイル: run.py プロジェクト: mdahteshamusa/word-count
def prepare_response(res):
    if res is not None and len(res) > 0:
        # make_response(jsonify(res)) - jsonify re-orders keys pushing highest freq words at bottom
        return Serializer.get(res)
    else:
        abort(404)
コード例 #17
0
ファイル: test_pagination.py プロジェクト: Kareeeeem/AMC
def test_empty_page(session):
    query = User.query
    page = Pagination(FakeRequest(), query)
    result = Serializer(UserSchema).dump_page(page)
    assert result['items'] == []