コード例 #1
0
ファイル: app.py プロジェクト: matemijolovic/rznu_lab1
def add_default_post_comments(user, posts):
    for post in posts:
        comment1 = Comment(content=f'I commented on my own post...',
                           user_id=user.id,
                           post_id=post.id)
        comment2 = Comment(content=f'Some comments here and there',
                           user_id=user.id,
                           post_id=post.id)
        db.session.add(comment1)
        db.session.add(comment2)
    db.session.commit()
コード例 #2
0
    def setUp(self):
        self.c = Client()
        self.credentials = {'username': '******', 'password': '******'}

        author = RedditUser.objects.create(user=User.objects.create_user(
            **self.credentials))

        submission = Submission.objects.create(
            author=author,
            author_name=author.user.username,
            title="vote testing")

        Comment.create(author=author,
                       raw_comment="root comment",
                       parent=submission).save()
コード例 #3
0
def post_comment(request):
    if not request.user.is_authenticated():
        return JsonResponse({'msg': "You need to log in to post new comments."})

    parent_type = request.POST.get('parentType', None)
    parent_id = request.POST.get('parentId', None)
    raw_comment = request.POST.get('commentContent', None)

    if not all([parent_id, parent_type]) or \
            parent_type not in ['comment', 'submission'] or \
        not parent_id.isdigit():
        return HttpResponseBadRequest()

    if not raw_comment:
        return JsonResponse({'msg': "You have to write something."})
    author = RedditUser.objects.get(user=request.user)
    parent_object = None
    try:  # try and get comment or submission we're voting on
        if parent_type == 'comment':
            parent_object = Comment.objects.get(id=parent_id)
        elif parent_type == 'submission':
            parent_object = Submission.objects.get(id=parent_id)

    except (Comment.DoesNotExist, Submission.DoesNotExist):
        return HttpResponseBadRequest()

    comment = Comment.create(author=author,
                             raw_comment=raw_comment,
                             parent=parent_object)

    comment.save()
    return JsonResponse({'msg': "Your comment has been posted."})
コード例 #4
0
    def post(self, id):
        args = request.json
        print(args)
        comment = Comment(topic_id=id,
                          parent_comment_id=args['parent_comment_id'],
                          content=args['content'],
                          created_by=self.db.query(User).first())

        self.db.add(comment)
        self.db.commit()
        return Response(json.dumps({
            'id':
            str(comment.id),
            'content':
            comment.content,
            'parent_id':
            str(comment.parent_comment_id)
            if comment.parent_comment_id else None,
            'created_by': {
                'id': str(comment.created_by_id),
                'email': comment.created_by.email,
            },
            'num_upvotes':
            int(comment.num_upvotes),
            'num_downvotes':
            int(comment.num_downvotes),
            'hotness_score':
            float(comment.hotness_score),
            'created_at':
            comment.created_at.isoformat(),
            'updated_at':
            comment.updated_at.isoformat(),
        }),
                        mimetype='application/json'), 201
コード例 #5
0
    def test_valid_comment_posting_reply(self):
        self.c.login(**self.credentials)
        thread = Submission.objects.get(id=99)
        author = RedditUser.objects.get(user=User.objects.get(
            username=self.credentials['username']
        ))
        comment = Comment.create(author, 'root comment', thread)
        comment.save()
        self.assertEqual(Comment.objects.filter(submission=thread).count(), 1)

        test_data = {
            'parentType': 'comment',
            'parentId': comment.id,
            'commentContent': 'thread reply comment'
        }

        r = self.c.post(reverse('Post Comment'), data=test_data)
        self.assertEqual(r.status_code, 200)
        json_r = json.loads(r.content)
        self.assertEqual(json_r['msg'], 'Your comment has been posted.')
        self.assertEqual(Comment.objects.filter(submission=thread).count(), 2)

        comment = Comment.objects.filter(submission=thread,
                                         id=2).first()
        self.assertEqual(comment.html_comment, u'<p>thread reply comment</p>\n')
コード例 #6
0
    def handle(self, *args, **options):
        self.thread_count = options['thread_count']
        self.root_comments = options['root_comments']
        self. random_usernames = [self.get_random_username() for _ in range(100)]
        for index, _ in enumerate(range(self.thread_count)):
            print("Thread {} out of {}".format(str(index), self.thread_count))
            selftext = self.get_random_sentence()
            title = self.get_random_sentence(max_words=100, max_word_len=10)
            author = self.get_or_create_author(choice(self.random_usernames))
            ups = randint(0, 1000)
            url = None
            downs = int(ups) / 2
            comments = 0

            submission = Submission(author=author,
                                    title=title,
                                    url=url,
                                    text=selftext,
                                    ups=int(ups),
                                    downs=downs,
                                    score=ups - downs,
                                    comment_count=comments)
            submission.generate_html()
            submission.save()

            for _ in range(self.root_comments):
                print("Adding thread comments...")
                comment_author = self.get_or_create_author(choice(self.random_usernames))
                raw_text = self.get_random_sentence(max_words=100)
                new_comment = Comment.create(comment_author, raw_text, submission)
                new_comment.save()
                another_child = choice([True, False])
                while another_child:
                    self.add_replies(new_comment)
                    another_child = choice([True, False])
コード例 #7
0
    def test_valid_comment_posting_reply(self):
        self.c.login(**self.credentials)
        thread = Submission.objects.get(id=99)
        author = RedditUser.objects.get(user=User.objects.get(
            username=self.credentials['username']
        ))
        comment = Comment.create(author, 'root comment', thread)
        comment.save()
        self.assertEqual(Comment.objects.filter(submission=thread).count(), 1)

        test_data = {
            'parentType': 'comment',
            'parentId': comment.id,
            'commentContent': 'thread reply comment'
        }

        r = self.c.post(reverse('post_comment'), data=test_data)
        self.assertEqual(r.status_code, 200)
        json_r = json.loads(r.content.decode("utf-8"))
        self.assertEqual(json_r['msg'], 'Your comment has been posted.')
        self.assertEqual(Comment.objects.filter(submission=thread).count(), 2)

        comment = Comment.objects.filter(submission=thread,
                                         id=2).first()
        self.assertEqual(comment.html_comment, '<p>thread reply comment</p>\n')
コード例 #8
0
    def add_replies(self, root_comment, depth=1):
        if depth > 5:
            return

        comment_author = self.get_or_create_author(choice(self.random_usernames))

        raw_text = self.get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            self.add_replies(new_comment, depth + 1)
コード例 #9
0
    def add_replies(self, root_comment, depth=1):
        if depth > 5:
            return

        comment_author = self.get_or_create_author(
            choice(self.random_usernames))

        raw_text = self.get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            self.add_replies(new_comment, depth + 1)
コード例 #10
0
ファイル: views.py プロジェクト: jeffthemaximum/jeffit_v2
    def add_replies(root_comment, depth=1):
        print "Adding comment replies..."
        if depth > 5:
            return

        comment_author = get_or_create_author(choice(random_usernames))

        raw_text = get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            add_replies(new_comment, depth + 1)
コード例 #11
0
ファイル: views.py プロジェクト: coderadi369/django_reddit
    def add_replies(root_comment, depth=1):
        print "Adding comment replies..."
        if depth > 5:
            return

        comment_author = get_or_create_author(choice(random_usernames))

        raw_text = get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            add_replies(new_comment, depth + 1)
コード例 #12
0
ファイル: test_voting.py プロジェクト: ajbeach2/django_reddit
    def setUp(self):
        self.c = Client()
        self.credentials = {
            'username': '******',
            'password': '******'
        }

        author = RedditUser.objects.create(
            user=User.objects.create_user(
                **self.credentials
            )
        )

        submission = Submission.objects.create(
            author=author,
            author_name=author.user.username,
            title="vote testing"
        )

        Comment.create(author=author,
                       raw_comment="root comment",
                       parent=submission).save()
コード例 #13
0
ファイル: subreddits.py プロジェクト: matemijolovic/rznu_lab1
def subreddit_post_comments(subreddit_id, post_id):
    post = find_post(subreddit_id, post_id)
    form = CommentForm(request.form)

    if request.method == 'GET':
        return render_template('single_post.html', post=post, form=form)

    if form.validate():
        comment = Comment(content=request.form.get('content'),
                          user_id=current_user.id,
                          post_id=post.id)
        db.session.add(comment)
        db.session.commit()
    return redirect(
        url_for('subreddits.subreddit_post',
                subreddit_id=subreddit_id,
                post_id=post_id))
コード例 #14
0
    def handle(self, *args, **options):
        self.thread_count = options['thread_count']
        self.root_comments = options['root_comments']
        self.random_usernames = [
            self.get_random_username() for _ in range(100)
        ]
        for index, _ in enumerate(range(self.thread_count)):
            print("Thread {} out of {}".format(str(index), self.thread_count))
            selftext = self.get_random_sentence()
            title = self.get_random_sentence(max_words=100, max_word_len=10)
            author = self.get_or_create_author(choice(self.random_usernames))
            ups = randint(0, 1000)
            url = None
            downs = int(ups) / 2
            comments = 0

            submission = Submission(author=author,
                                    title=title,
                                    url=url,
                                    text=selftext,
                                    ups=int(ups),
                                    downs=downs,
                                    score=ups - downs,
                                    comment_count=comments)
            submission.generate_html()
            submission.save()

            for _ in range(self.root_comments):
                print("Adding thread comments...")
                comment_author = self.get_or_create_author(
                    choice(self.random_usernames))
                raw_text = self.get_random_sentence(max_words=100)
                new_comment = Comment.create(comment_author, raw_text,
                                             submission)
                new_comment.save()
                another_child = choice([True, False])
                while another_child:
                    self.add_replies(new_comment)
                    another_child = choice([True, False])
コード例 #15
0
ファイル: views.py プロジェクト: jeffthemaximum/jeffit_v2
def test_data(request):  # pragma: no cover
    """
    Quick and dirty way to create 10 random submissions random comments each
    and up to 100 users with usernames (their passwords are same as usernames)

    Should be removed in production.

    """
    get_page = """
    <form action="/populate/" method="POST">
    Threads: <input type="number" name="threads" value=10></input>
    Root comments: <input type="number" name="comments" value=10></input>
    <button type="submit">Create</button>
    </form>
    """
    if not request.user.is_authenticated() or not request.user.is_staff:
        return Http404()

    if request.method == "GET":
        return HttpResponse(get_page)

    thread_count = int(request.POST.get('threads', 10))
    root_comments = int(request.POST.get('comments', 10))

    from random import choice, randint
    from string import letters

    def get_random_username(length=6):
        return ''.join(choice(letters) for _ in range(length))

    random_usernames = [get_random_username() for _ in range(100)]

    def get_random_sentence(min_words=3, max_words=50,
                            min_word_len=3,
                            max_word_len=15):
        sentence = ''

        for _ in range(0, randint(min_words, max_words)):
            sentence += ''.join(choice(letters)
                                for i in
                                range(randint(min_word_len, max_word_len)))
            sentence += ' '

        return sentence

    def get_or_create_author(username):
        try:
            user = User.objects.get(username=username)
            author = RedditUser.objects.get(user=user)
        except (User.DoesNotExist, RedditUser.DoesNotExist):
            print "Creating user {}".format(username)
            new_author = User(username=username)
            new_author.set_password(username)
            new_author.save()
            author = RedditUser(user=new_author)
            author.save()
        return author

    def add_replies(root_comment, depth=1):
        print "Adding comment replies..."
        if depth > 5:
            return

        comment_author = get_or_create_author(choice(random_usernames))

        raw_text = get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            add_replies(new_comment, depth + 1)

    for _ in range(thread_count):
        print "Creating new submission."
        selftext = get_random_sentence()
        title = get_random_sentence(max_words=100, max_word_len=10)
        author = get_or_create_author(choice(random_usernames))
        ups = randint(0, 1000)
        url = None
        downs = int(ups) / 2
        comments = 0

        submission = Submission(author=author,
                                title=title,
                                url=url,
                                text=selftext,
                                ups=int(ups),
                                downs=downs,
                                score=ups - downs,
                                comment_count=comments)
        submission.generate_html()
        submission.save()

        for _ in range(root_comments):
            comment_author = get_or_create_author(choice(random_usernames))
            raw_text = get_random_sentence(max_words=100)
            new_comment = Comment.create(comment_author, raw_text, submission)
            new_comment.save()
            another_child = choice([True, False])
            while another_child:
                add_replies(new_comment)
                another_child = choice([True, False])

    return redirect('/')
コード例 #16
0
ファイル: views.py プロジェクト: coderadi369/django_reddit
def test_data(request):  # pragma: no cover
    """
    Quick and dirty way to create 10 random submissions random comments each
    and up to 100 users with usernames (their passwords are same as usernames)

    Should be removed in production.

    """
    get_page = """
    <form action="/populate/" method="POST">
    Threads: <input type="number" name="threads" value=10></input>
    Root comments: <input type="number" name="comments" value=10></input>
    <button type="submit">Create</button>
    </form>
    """
    if not request.user.is_authenticated() or not request.user.is_staff:
        return Http404()

    if request.method == "GET":
        return HttpResponse(get_page)

    thread_count = int(request.POST.get('threads', 10))
    root_comments = int(request.POST.get('comments', 10))

    from random import choice, randint
    from string import letters

    def get_random_username(length=6):
        return ''.join(choice(letters) for _ in range(length))

    random_usernames = [get_random_username() for _ in range(100)]

    def get_random_sentence(min_words=3,
                            max_words=50,
                            min_word_len=3,
                            max_word_len=15):
        sentence = ''

        for _ in range(0, randint(min_words, max_words)):
            sentence += ''.join(
                choice(letters)
                for i in range(randint(min_word_len, max_word_len)))
            sentence += ' '

        return sentence

    def get_or_create_author(username):
        try:
            user = User.objects.get(username=username)
            author = RedditUser.objects.get(user=user)
        except (User.DoesNotExist, RedditUser.DoesNotExist):
            print "Creating user {}".format(username)
            new_author = User(username=username)
            new_author.set_password(username)
            new_author.save()
            author = RedditUser(user=new_author)
            author.save()
        return author

    def add_replies(root_comment, depth=1):
        print "Adding comment replies..."
        if depth > 5:
            return

        comment_author = get_or_create_author(choice(random_usernames))

        raw_text = get_random_sentence()
        new_comment = Comment.create(comment_author, raw_text, root_comment)
        new_comment.save()
        if choice([True, False]):
            add_replies(new_comment, depth + 1)

    for _ in range(thread_count):
        print "Creating new submission."
        selftext = get_random_sentence()
        title = get_random_sentence(max_words=100, max_word_len=10)
        author = get_or_create_author(choice(random_usernames))
        ups = randint(0, 1000)
        url = None
        downs = int(ups) / 2
        comments = 0

        submission = Submission(author=author,
                                title=title,
                                url=url,
                                text=selftext,
                                ups=int(ups),
                                downs=downs,
                                score=ups - downs,
                                comment_count=comments)
        submission.generate_html()
        submission.save()

        for _ in range(root_comments):
            comment_author = get_or_create_author(choice(random_usernames))
            raw_text = get_random_sentence(max_words=100)
            new_comment = Comment.create(comment_author, raw_text, submission)
            new_comment.save()
            another_child = choice([True, False])
            while another_child:
                add_replies(new_comment)
                another_child = choice([True, False])

    return redirect('/')