Пример #1
0
def register():
    payload = request.get_json()
    if not payload:
        raise InvalidUsage.validation_error()

    try:
        # Prevent user schema from breaking with no password field
        password = payload["password"]
        del payload["password"]

        data = user_schema.load(payload)
        data["password"] = password
    except ValidationError as ex:
        raise InvalidUsage.validation_error()
    except KeyError as ex:
        raise InvalidUsage.validation_error()
    except AssertionError as ex:
        raise InvalidUsage.unknown_error()

    user = User(**data)
    user.save()
    user_data = user_schema.dump(user)
    access_token = create_access_token(user)
    return jsonify(data={'token': access_token},
                   message="Registration successful.",
                   status=201), 201
Пример #2
0
def subscribe(subreddit):
    subreddit = Subreddit.query.filter_by(name=subreddit).first()
    if not subreddit:
        raise InvalidUsage.resource_not_found()

    try:
        subreddit.subscribe(current_user)
    except exc.IntegrityError:
        raise InvalidUsage.duplicate()
    return jsonify(message='Subscribed.', status=204)
Пример #3
0
def unsubscribe(subreddit):
    subreddit = Subreddit.query.filter_by(name=subreddit).first()
    if not subreddit:
        raise InvalidUsage.resource_not_found()

    try:
        subreddit.unsubscribe(current_user)
    except ValueError as ex:
        raise InvalidUsage.resource_not_found()
    except Exception as ex:
        raise InvalidUsage.unknown_error()

    return jsonify(message='Unsubscribed.', status=204)
Пример #4
0
def update_vote(thread=None, direction=None):
    vote = Vote.get(current_user.id, thread)
    thread = Thread.get_or_404(thread)
    if not vote:
        raise InvalidUsage.resource_not_found()

    try:
        thread.update_vote(vote)
        vote.update(direction, commit=False)
        thread.save()
    except Exception as ex:
        db.session.rollback()
        raise InvalidUsage.duplicate()
    return dict(message='Vote updated.', status=204), 204
Пример #5
0
def create_subreddit():
    data = request.get_json()
    try:
        subreddit_data = subreddit_schema.load(data)
        subreddit = Subreddit(creator_id=current_user.id, **subreddit_data)
        subreddit.save()

        subreddit.subscribe(current_user)
    except ValidationError as ex:
        raise InvalidUsage.validation_error()
    except exc.IntegrityError as ex:
        raise InvalidUsage.duplicate()
    subreddit_data = subreddit_schema.dump(subreddit)
    return jsonify(data=subreddit_data,
                   message='Subreddit created.',
                   status=201), 201
Пример #6
0
def get_subreddit_threads(name):
    subreddit = Subreddit.query.filter_by(name=name).first()
    if not subreddit:
        raise InvalidUsage.resource_not_found()

    data = subreddit.threads.order_by(Thread.createdAt.desc()).all()
    data = threads_schema.dump(data)
    return jsonify(data=data, status=200)
Пример #7
0
def get_subscribers(name):
    subreddit = Subreddit.query.filter_by(name=name).first()
    if not subreddit:
        raise InvalidUsage.resource_not_found()

    return jsonify(data={
        'subscribers': [user.username for user in subreddit.subscribers]
    },
                   status=200)
Пример #8
0
def create_vote(thread=None, direction=None):
    if not direction or direction not in [-1, 1]:
        raise InvalidUsage.validation_error()

    thread = Thread.get_or_404(thread)

    try:
        vote = Vote(voter_id=current_user.id,
                    voted_thread_id=thread.id,
                    direction=direction)
        vote.save(commit=False)
        thread.add_vote(vote)
        thread.save(commit=True)
    except exc.IntegrityError as ex:
        db.session.rollback()
        raise InvalidUsage.duplicate()
    vote_data = vote_schema.dump(vote)
    return dict(message='Vote created', status=201), 201
Пример #9
0
def login():
    payload = request.get_json()
    if not payload:
        raise InvalidUsage.unknown_error()

    try:
        username = payload["username"]
        password = payload["password"]
    except KeyError as ex:
        raise InvalidUsage.unknown_error()

    user = User.query.filter_by(username=username).first()
    if not user or not user.verify(password):
        raise InvalidUsage.auth_failure()

    access_token = create_access_token(user)

    return jsonify(status=200, message='Success', data={'token':
                                                        access_token}), 200
Пример #10
0
def search():
    try:
        query = request.args['q']
    except KeyError as ex:
        raise InvalidUsage.validation_error()
    
    search = Search(index='threads')
    search.query = MultiMatch(query=query, fields=['title', 'body', 'description'])
    response = search.execute()
    return jsonify(response.to_dict())
Пример #11
0
 def get_from_cache(cls, id):
     cache = cls.cache
     key = cls.make_cache_key(id)
     logger.info(f"Getting cached key {key}")
     cached = cache.get(key)
     logger.info(f"Read cached value {cached}")
     if cached:
         if cached == INVALID_HASH:
             raise InvalidUsage.resource_not_found()
         cached = cls._serializer.load(cached)
     return cached
Пример #12
0
        def decorated(*args, **kwargs):
            if primary_key:
                object = model.query.get(kwargs.get(field))
            else:
                kwargs = {field: kwargs.get(field)}
                object = model.query.filter_by(**kwargs).first()

            if not object:
                raise InvalidUsage.resource_not_found()

            result = f(object, *args, **kwargs)

            return result
Пример #13
0
def get_votes(thread=None, user=None):
    if (thread is None and user is None) \
            or (thread is not None and user is not None):
        raise InvalidUsage.validation_error()

    res = Vote.query
    schema = None
    if thread:
        res = res.filter_by(voted_thread_id=thread).all()
        schema = thread_votes_schema
    elif user:
        res = res.filter_by(voter_id=user).all()
        schema = user_votes_schema
    return jsonify(data=schema.dump(res))
Пример #14
0
 def get_from_db(cls, id, strict=False):
     obj = cls.query.get(id)
     if not obj and strict:
         raise InvalidUsage.resource_not_found()
     return obj