Beispiel #1
0
def seed_comments(num_of_comments):
    users = User.query.all()
    posts = Post.query.all()
    comments_list = []

    try:
        print('Fetching comments...')
        for i in range(int(num_of_comments/500)):
            comments_list.extend(requests.get(
                'https://jsonplaceholder.typicode.com/comments').json())

        comments = [comment.get('body') for comment in comments_list]

        comments_list = []

        for c in comments:
            user = random.choice(users)
            post = random.choice(posts)

            comment = Post(body=c)
            comment.user_id = user.id
            comment.comment_id = post.id
            comment.created_on = random_timestamp(
                datetime(2021, 1, 1), datetime(2021, 2, 11))
            comment.likes.extend(random.sample(users, k=random.randrange(12)))
            comments_list.append(comment)

        print('Saving to database...')
        db.session.add_all(comments_list)
        db.session.commit()

    except Exception as error:
        print(f'Error: {error}')
Beispiel #2
0
def seed_posts(num_of_posts):
    """
    Seed the database with some posts.
    """
    users = User.query.all()
    posts1 = []
    posts2 = []
    post_objs = []

    print('Fetching posts...')

    for i in range(int(num_of_posts/10)):
        posts1.extend(requests.get(
            'https://official-joke-api.appspot.com/jokes/ten').json())

    for i in range(20):
        posts2.extend(requests.get(
            f'https://icanhazdadjoke.com/search?limit=30&page={i}',
            headers={'accept': 'application/json'}).json().get('results'))

    try:
        print('Saving posts to database...')
        for p in posts1:
            user = random.choice(users)

            post = Post()
            post.body = f"{p.get('setup')} - {p.get('punchline')}"
            post.user_id = user.id
            post.likes.extend(random.sample(users, k=random.randrange(36)))
            post.created_on = random_timestamp(
                datetime.datetime(2019, 1, 1), datetime.datetime(2019, 7, 30))
            # post.tags.extend(item.)
            post_objs.append(post)

        for item in posts2:
            user = random.choice(users)

            post = Post()
            post.body = item.get('joke')
            post.user_id = user.id
            post.created_on = random_timestamp(
                datetime.datetime(2019, 7, 1), datetime.datetime(2020, 1, 31))
            post.likes.extend(random.sample(users, k=random.randrange(30)))
            post_objs.append(post)

        db.session.add_all(post_objs)
        db.session.commit()

        print(f'Post table seeded with {num_of_posts} posts...')
    except Exception as error:
        print(f'Error: {error}')
Beispiel #3
0
def get_post_comments(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    if cursor == '0':
        query = post.comments.order_by(
            Post.created_on.desc()).limit(items_per_page + 1).all()
    else:
        cursor = urlsafe_base64(cursor, from_base64=True)
        query = post.comments.order_by(Post.created_on.desc()).filter(
            Post.created_on < cursor).limit(items_per_page + 1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(query[items_per_page -
                                          1].created_on.isoformat())

    comments = []
    for c in query[:items_per_page]:
        comment = c.to_dict(user)
        comment['parent'] = PostSchema(only=(
            'id',
            'body',
            'author',
        )).dump(c.parent)
        comments.append(comment)

    return {'data': comments, 'nextCursor': nextCursor}
Beispiel #4
0
def update_like(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found')

    try:
        if post.is_liked_by(user):
            post.likes.remove(user)
            db.session.delete(
                Notification.find_by_attr(subject='like', item_id=post.id))
        else:
            post.likes.append(user)
            db.session.add(
                user.add_notification('like',
                                      item_id=post.id,
                                      id=post.author.id,
                                      post_id=post.id))

        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(post.to_dict(user))
Beispiel #5
0
def get_tag_posts(user, tag_name):
    top = request.args.get('top', default=False)
    latest = request.args.get('latest', default=False)
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        tag = Tag.query.filter_by(name=tag_name).first()
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured.')

    try:
        sorted_posts = Post.get_by_reactions().subquery()
        tag_posts = Post.query.with_parent(tag).subquery()
        sort_top_posts = db.session.query(
            tag_posts, sorted_posts.c.sequence).join(
                sorted_posts, sorted_posts.c.id == tag_posts.c.id).subquery()
        top_posts = db.session.query(Post, sort_top_posts.c.sequence).join(
            sort_top_posts, Post.id == sort_top_posts.c.id).order_by(
                sort_top_posts.c.sequence.desc())
        latest_posts = Post.query.with_parent(tag).order_by(
            Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and latest:
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and top:
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if latest:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                sort_top_posts.c.sequence < cursor).limit(items_per_page +
                                                          1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1].created_on.isoformat()) \
                if latest else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    posts = [post.to_dict(user) for post in query[:items_per_page]] \
        if latest else \
            [post[0].to_dict(user) for post in query[:items_per_page]]

    return {'data': posts, 'nextCursor': nextCursor}
Beispiel #6
0
def posts_feed(user):
    latest = request.args.get('latest')
    top = request.args.get('top')
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        followed_posts = user.get_followed_posts().subquery()
        posts_reactions = Post.get_reactions().subquery()
        top_followed_posts = db.session.query(
            followed_posts,
            func.row_number().over(order_by=posts_reactions.c.reactions).
            label('sequence')).outerjoin(
                posts_reactions,
                followed_posts.c.posts_id == posts_reactions.c.id).subquery()

        top_posts = db.session.query(Post, top_followed_posts.c.sequence).join(
            Post, top_followed_posts.c.posts_id == Post.id).order_by(
                top_followed_posts.c.sequence.desc())

        latest_posts = db.session.query(Post, followed_posts.c.posts_id).join(
            Post, Post.id == followed_posts.c.posts_id).order_by(
                Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and latest:
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and top:
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if latest:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                top_followed_posts.c.sequence < cursor).limit(items_per_page +
                                                              1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1][0].created_on.isoformat()) \
                if latest else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    return {
        'data': [post[0].to_dict(user) for post in query[:items_per_page]],
        'nextCursor': nextCursor
    }
Beispiel #7
0
def get_post(user, post_id):
    try:
        print(post_id)
        post = Post.find_by_id(post_id)

        if not post:
            return not_found('Post not found')
    except Exception:
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(PostSchema().dump(post))
Beispiel #8
0
def add_post(body, user_id, comments=[]):
    post = Post()
    post.body = body
    post.user_id = user_id

    if comments:
        post.comments.extend(comments)

    post.save()
    return post
Beispiel #9
0
def create_post(user, post_id=None):
    req_data = request.get_json()

    if not req_data:
        return bad_request("No request data provided")

    post = Post()
    post.body = req_data.get('post')
    post.user_id = user.id
    db.session.add(post)

    if post_id:
        post.comment_id = post_id
        parent = Post.find_by_id(post_id)
        db.session.add(
            user.add_notification(subject='comment',
                                  item_id=post.id,
                                  id=parent.author.id,
                                  post_id=parent.id))
    else:
        post_notifs = []
        for u in user.followers.all():
            post_notifs.append(
                user.add_notification(subject='post',
                                      item_id=post.id,
                                      id=u.id,
                                      post_id=post.id))
        db.session.add_all(post_notifs)

    try:
        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        response = jsonify(post.to_dict(user))
        response.status_code = 201
        response.headers['Location'] = url_for('posts.get_post',
                                               post_id=post.id)
        return response
Beispiel #10
0
def delete_post(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    if post.user_id != user.id:
        return error_response(401, "You cannot delete someone else's post.")

    try:
        post.delete()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(PostSchema().dump(post.id))
Beispiel #11
0
def get_post(user, post_id):
    try:
        post = Post.find_by_id(post_id)

        if not post:
            return not_found('Post not found')
    except Exception:
        return server_error('Something went wrong, please try again.')
    else:
        post_dict = post.to_dict(user)
        post_dict['isLiked'] = post.is_liked_by(user)

        if user.id != post.author.id:
            post_dict['author']['isFollowing'] = user.is_following(post.author)

        return jsonify(post_dict)
Beispiel #12
0
def get_posts(user):
    feed = request.args.get('feed')
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        sorted_posts = Post.get_by_reactions().subquery()
        top_posts = db.session.query(Post, sorted_posts.c.sequence).join(
            sorted_posts, sorted_posts.c.id == Post.id).order_by(
                sorted_posts.c.sequence.desc())
        latest_posts = Post.query.filter(Post.comment_id.is_(None)).order_by(
            Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and feed == 'latest':
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and feed == 'top':
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if feed == 'latest':
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                sorted_posts.c.sequence < cursor).limit(items_per_page +
                                                        1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1].created_on.isoformat()) \
                if feed == 'latest' else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    posts = [post.to_dict(user) for post in query[:items_per_page]] \
        if feed == 'latest' else \
            [post[0].to_dict(user) for post in query[:items_per_page]]

    return {'data': posts, 'nextCursor': nextCursor}
Beispiel #13
0
def get_comments(user, post_id, page=1):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    try:
        comments = Comment.query.with_parent(post).order_by(
                Comment.created_on.desc()).paginate(
            page, current_app.config['ITEMS_PER_PAGE'])
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'comments': CommentSchema(many=True).dump(comments.items),
            'hasNext': comments.has_next,
        }
Beispiel #14
0
def update_like(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found')

    try:
        if post.is_liked_by(user):
            post.likes.remove(user)
        else:
            post.likes.append(user)

        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(PostSchema().dump(post))
Beispiel #15
0
def update_post(user, post_id):
    post_data = request.get_json()
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    if post.user_id != user.id:
        return error_response(401, "You cannot update someone else's post.")

    post.body = post_data.get('post')

    try:
        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return jsonify(PostSchema().dump(post))
Beispiel #16
0
def add_post(body, user, post_id=None):
    post = Post()
    post.body = body
    post.user_id = user.id

    if post_id:
        post.comment_id = post_id

    post_notifs = []
    for u in user.followers.all():
        post_notifs.append(
            user.add_notification(subject='post',
                                  item_id=post.id,
                                  id=u.id,
                                  post_id=post.id))

    db.session.add_all(post_notifs)
    post.save()
    return post
Beispiel #17
0
def delete_post(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    if post.user_id != user.id:
        return error_response(401, "You cannot delete someone else's post.")

    post_notif = Notification.find_by_attr(subject='post', item_id=post.id)
    comment_notif = Notification.find_by_attr(subject='comment',
                                              item_id=post.id)

    [db.session.delete(notif) for notif in post_notif] if post_notif \
        else db.session.delete(comment_notif)

    try:
        post.delete()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return {'message': 'Post was successfuly deleted.'}
Beispiel #18
0
def create_post(user):
    post_data = request.get_json()
    print(post_data)

    post = Post()
    post.body = post_data.get('post')
    post.user_id = user.id

    try:
        post.save()
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        response = jsonify(PostSchema().dump(post))
        response.status_code = 201
        response.headers['Location'] = url_for(
            'posts.get_post', post_id=post.id)
        return response
Beispiel #19
0
def seed_posts(num_of_posts):
    """Seed the database with some posts."""
    users = User.query.all()
    posts1 = []
    posts2 = []
    post_objs = []
    tag_list = ['safe', 'broad', 'witty', 'humorous']

    print('Fetching posts...')

    for i in range(int(num_of_posts/15)):
        posts1.extend(requests.get(
            'https://official-joke-api.appspot.com/jokes/ten').json())

    for i in range(int(num_of_posts/15)):
        posts2.extend(requests.get(
            'https://sv443.net/jokeapi/v2/joke/Any?\
                blacklistFlags=nsfw,racist,sexist&type=twopart&amount=10',
            headers={'accept': 'application/json'}).json().get('jokes'))

    try:
        print('Saving posts to database...')
        for p in posts1:
            user = random.choice(users)

            tag = p.get('type')
            tags = [tag, random.choice(tag_list)]
            body = f"{p.get('setup')} - {p.get('punchline')}"

            post = Post()
            post.body = body
            post.user_id = user.id

            post.likes.extend(random.sample(users, k=random.randrange(36)))
            post.created_on = random_timestamp(
                datetime(2020, 7, 1), datetime(2020, 9, 28))

            for t in tags:
                tag = Tag.query.filter_by(name=t).first()

                if tag:
                    post.tags.append(tag)
                else:
                    tag = Tag(name=t)
                    db.session.add(tag)
                    post.tags.append(tag)

            post_objs.append(post)

        for p in posts2:
            user = random.choice(users)

            tag = p.get('category').lower()
            flags = p.get('flags')
            tags = [key.lower() for key in flags if flags[key] is True]
            tags.append(tag)
            if bool(p.get('safe')):
                tags.append('safe')

            body = f"{p.get('setup')} - {p.get('delivery')}"

            post = Post()
            post.body = body
            post.user_id = user.id
            post.created_on = random_timestamp(
                datetime(2020, 9, 1), datetime(2020, 12, 31))
            post.likes.extend(random.sample(users, k=random.randrange(30)))

            for t in tags:
                tag = Tag.query.filter_by(name=t).first()

                if tag:
                    post.tags.append(tag)
                else:
                    tag = Tag(name=t)
                    db.session.add(tag)
                    post.tags.append(tag)

            post_objs.append(post)

        db.session.add_all(post_objs)
        db.session.commit()

        print(f'Post table seeded with {num_of_posts} posts...')
    except Exception as error:
        print(f'Error: {error}')