Example #1
0
def new_post(request):
    # data is passed as a string and needs to be converted to a dict
    data = json.loads(request.data['data'])
    client = get_object_or_404(Client, user=request.user)

    if request.data.get('file'):
        data['image'] = request.data['file']

    if 'blog' in data:
        blog = get_object_or_404(Blog, id=data['blog'])
    else:
        topic = Topic.objects.get(name="Personal")
        blog = Blog.objects.get(topic=topic, owner__in=[client])
        data.update({'blog': blog.id})

    # check permissions to create new post on this blog
    if not blog.isPublic and client not in blog.subs.all():
        data = {'error': 'not enough permissions'}
    else:
        data.update({'client': client.id})
        post_serializer = PostSerializer(data=data)

        if post_serializer.is_valid():
            post_serializer.save()
            data = {
                'success': 'successfully created a new post',
                'post': post_serializer.data
            }
        else:
            data = post_serializer.errors

    return Response(data)
Example #2
0
    def update(self, request, *args, **kwargs):
        pk = kwargs['pk']
        snippet = self.get_object(pk)
        if snippet.author != request.user.id:
            return Response({"error": "only author can update post"},
                            status=status.HTTP_400_BAD_REQUEST)

        data = request.data.dict()

        if not data.get('title'):
            data['title'] = snippet.title

        if not data.get('text'):
            data['text'] = snippet.title

        data['author'] = snippet.author.id
        data['liked'] = snippet.liked
        data['liked'] = snippet.unliked
        data['liked'] = snippet.total_liked

        serializer = PostSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #3
0
 def post(self, request, format=None):
     print 'In post hander'
     user = request.user
     serializer = PostSerializer(data=request.data, context={'user':user})
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def test_post_serializer_is_invalid(self):
        post_obj_data = {
            u'title': u'title',
            u'code': u'code',
            u'ttl_option': u'minutes=10',
            u'syntax': "1"
        }
        post_serializer = PostSerializer(data=post_obj_data)

        self.assertFalse(post_serializer.is_valid())
Example #5
0
	def test_post_serializer_is_invalid(self):
		post_obj_data = {
			u'title': u'title', 
			u'code': u'code', 
			u'ttl_option': u'minutes=10',
			u'syntax': "1"
		}
		post_serializer = PostSerializer(data=post_obj_data)
		
		self.assertFalse(post_serializer.is_valid())
Example #6
0
    def patch(self, request, pk):
        post = get_object_or_404(Post, pk=pk)

        data = {"amount_of_upvotes": post.amount_of_upvotes + 1}
        serializer = PostSerializer(post, data=data, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #7
0
	def test_post_serializer_is_valid(self):
		Syntax.objects.create(syntax_name="syntax_name1")
		post_obj_data = {
			u'title': u'title', 
			u'code': u'code', 
			u'ttl_option': u'minutes=10',
			u'syntax': "1"
		}
		post_serializer = PostSerializer(data=post_obj_data)
		
		self.assertTrue(post_serializer.is_valid())
Example #8
0
    def test_post_serializer_is_valid(self):
        Syntax.objects.create(syntax_name="syntax_name1")
        post_obj_data = {
            u'title': u'title',
            u'code': u'code',
            u'ttl_option': u'minutes=10',
            u'syntax': "1"
        }
        post_serializer = PostSerializer(data=post_obj_data)

        self.assertTrue(post_serializer.is_valid())
Example #9
0
    def put(self, request, pk, format=None):
        post = self.get_object(pk)
        self.check_object_permissions(self.request, post)

        if post.category != request.data.get('category'):
            return Response(status=status.HTTP_400_BAD_REQUEST)

        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #10
0
 def post(self):
     form = PostCreateForm()
     if not form.validate_on_submit():
         return form.errors, 422
     post = Post(form.title.data, form.body.data)
     db.session.add(post)
     db.session.commit()
     return PostSerializer(post).data, 201
Example #11
0
 def test_post_list(self):
     """Test retrieving a list of posts"""
     create_runnings()
     res = self.client.get(POSTS_URL)
     posts = Post.objects.order_by('-date')[:10]
     serializer = PostSerializer(posts, many=True)
     self.assertEqual(res.status_code, status.HTTP_200_OK)
     self.assertEqual(res.data['results'], serializer.data)
Example #12
0
def user_posts_detail(request, pk, pk_post):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        print(pk)
        print(pk_post)
        snippets = Post.objects.get(id=pk_post, profile=pk)
        serializer = PostSerializer(snippets, many=False)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        original = Post.objects.get(id=pk_post, profile=pk)
        serializer = PostSerializer(original, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        Post.objects.get(id=pk_post, profile=pk).delete()
        return JsonResponse({"Deleted": "True"}, status=201, safe=False)

    return JsonResponse({"Method Not Allowed": "True"}, status=405)
Example #13
0
def PostList(request):
    if request.method == 'GET':
        #posts = Post.objects.select_related().annotate(username=F('user__username')).annotate(password=F('user__password')).order_by('-timestamp')
        posts = Post.objects.select_related().extra(
            select={
                'username': '******',
                'password': '******'
            }).order_by('-timestamp')
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)
Example #14
0
 def test_post_list_with_filter(self):
     """Test filtered retrieving a list of post"""
     create_runnings()
     res = self.client.get(POSTS_URL, {
         'me': 'true',
         'status': Post.Status.ERROR_PARSE
     })
     posts = Post.objects.filter(
         last_update__isnull=False,
         status=Post.Status.ERROR_PARSE).order_by('date')
     serializer = PostSerializer(posts, many=True)
     self.assertEqual(res.status_code, status.HTTP_200_OK)
     self.assertEqual(res.data['results'], serializer.data)
Example #15
0
    def test_retrieve(self):
        config = {'url': '/users/1/posts/1/', 'pk': 1}

        response = self.client.get(self.SERVER_NAME + config['url'],
                                   format='json')

        self.assertEqual(response.status_code, 200)

        objects = Post.objects.get(pk=config['pk'])
        data = PostSerializer(objects).data
        content = json.loads(response.content)

        self.assertEqual(content, data)
Example #16
0
    def test_list(self):
        config = {'url': '/users/1/posts/', 'user_id': 1}

        response = self.client.get(self.SERVER_NAME + config['url'],
                                   format='json')

        self.assertEqual(response.status_code, 200)

        objects = Post.objects.filter(user_id=config['user_id'])
        data = PostSerializer(objects, many=True).data
        content = json.loads(response.content)

        self.assertEqual(content, data)
Example #17
0
def like_post(request):
    client = get_object_or_404(Client, user=request.user)
    data = request.data
    post_id = data['post']
    post = get_object_or_404(Post, id=post_id)

    message = ""
    if client in post.likes.all():
        message = "Successfully removed like"
        post.likes.remove(client)
    else:
        message = "Successfully added like"
        post.likes.add(client)
    post.save()

    return Response({"success": message, 'post': PostSerializer(post).data})
Example #18
0
def _analyze_post_text(text: str, text_hash: str, last_sum_distance: int,
                       last_post_number: int, post: Post,
                       event_type: EventType) -> bool:
    parser_out = message_parser.parse(text)

    post.text = text
    post.text_hash = text_hash
    if parser_out:
        distance = parser_out.distance
        new_sum_distance = last_sum_distance + distance

        if parser_out.start_sum_number == last_sum_distance:
            if new_sum_distance == parser_out.end_sum_number:
                status = Post.Status.SUCCESS
            else:
                status = Post.Status.ERROR_SUM
        else:
            status = Post.Status.ERROR_START_SUM

        number = last_post_number + 1
    else:
        status = Post.Status.ERROR_PARSE
        number = None
        distance = None
        new_sum_distance = None

    # Check that sum expression is changed
    if (post.number != number or post.distance != distance
            or post.sum_distance != new_sum_distance or post.status != status):

        post.number = number
        post.distance = distance
        post.sum_distance = new_sum_distance
        post.status = status

        post.save()
        logger.debug(f' -- {event_type.name} post after analyze: {post}')

        # Adding status comment for post
        comment_text = _create_comment_text(post, last_sum_distance,
                                            new_sum_distance)
        _add_status_comment(post.id, comment_text)

        ws_service.main_group_send(
            PostSerializer(post).data, ObjectType.POST, event_type)

    return parser_out is not None
Example #19
0
def user_posts(request, pk):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Post.objects.filter(profile=pk)
        serializer = PostSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

    return JsonResponse({"Method Not Allowed": "True"}, status=405)
Example #20
0
    def test_update(self):
        config = {
            'url': '/users/1/posts/1/',
            'pk': 1,
            'payload': {
                'id': 1,
                'user': 1,
                'content': 'Hai bosulica',
            },
        }

        response = self.client.put(self.SERVER_NAME + config['url'],
                                   config['payload'],
                                   format='json')
        serializer = PostSerializer(Post.objects.get(pk=config['pk']))

        self.assertEqual(response.status_code, 200)

        for key, value in config['payload'].items():
            self.assertEqual(value, serializer.data[key])
Example #21
0
def main_posts(request):

    # get the client that did the request
    client = get_object_or_404(Client, user=request.user)

    # get the blogs that the client subscribed and order the posts by recent
    post_blogs = Blog.objects.filter(subs__in=[client])
    posts = Post.objects.filter(blog__in=post_blogs).order_by("-date")

    search = request.GET.get("search")
    choice = request.GET.get("order")
    order = request.GET.get("orderBy")

    if search is None:
        search = ""

    posts = (Post.objects.filter(title__contains=search, blog__in=post_blogs) \
             | Post.objects.filter(client__user__username__contains=search, blog__in=post_blogs))

    if order == "asc":
        order = ""
    elif order == "desc":
        order = "-"

    if choice == "recent":
        posts = posts.order_by(order + "date")
    elif choice == "likes":
        posts = posts.annotate(count=Count("likes")).order_by(order + "count")
    elif choice == "comments":
        posts = posts.annotate(count=Count("comment")).order_by(order +
                                                                "count")

    posts = PostSerializer(posts, many=True).data
    for post in posts:
        if client.id in post['likes']:  # post.likes:
            post['liked'] = True

    return Response(posts)
Example #22
0
 def post(self, request, format=None):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save(owner=request.user)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #23
0
 def get(self, request):
     post = Post.objects.filter(
         Q(user_id__in=request.user.profile.get_followers)
         | Q(user_id=request.user.id))
     ser = PostSerializer(post, many=True)
     return Response(ser.data)
Example #24
0
 def get(self, request):
     tweets = Post.objects.filter(user=request.user)
     ser = PostSerializer(tweets, many=True).data
     return Response(ser)
Example #25
0
 def get(self, request):
     tweets = Post.objects.all()
     ser = PostSerializer(tweets, many=True)
     return Response(ser.data)
Example #26
0
 def retrieve(self, request, *args, **kwargs):
     post = Post.objects.filter(id=kwargs['pk'])
     serializer = PostSerializer(post, many=True)
     return Response(serializer.data)
Example #27
0
File: views.py Project: nvetrov/d9
 def post(self, request, *args, **kwargs):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #28
0
 def get(self, id):
     posts = Post.query.filter_by(id=id).first()
     return PostSerializer(posts).data
Example #29
0
 def get(self, request):
     ser = PostSerializer(Profile.objects.get(user=request.user))
     return Response(ser.data)
Example #30
0
 def get(self):
     posts = Post.query.all()
     return PostSerializer(posts, many=True).data
Example #31
0
 def get(self, request):
     obj = Post.objects.filter(user__profile__id=request.GET.get('pk'))
     ser = PostSerializer(obj, many=True).data
     return Response(ser)
Example #32
0
 def get(self, request, pk, format=None):
     post = self.get_object(pk)
     serializer = PostSerializer(post)
     return Response(serializer.data)