예제 #1
0
def post_add(request):
    if request.method == 'PUT':
        data = JSONParser().parse(request)
        if 'post_data' in data:
            hash = calcHash(data['post_data'])
            data['post_uniqueCode'] = hash
        else:
            return HttpResponse("Bad syntax", status=400)

        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            try:
                post = Post.objects.get(
                    post_uniqueCode=data['post_uniqueCode'])
                if post != None:
                    return HttpResponse(
                        "post with requested code already exists", status=409)
            except Post.DoesNotExist:
                serializer.save()
                id = serializer.data['post_id']
                return HttpResponse(str(id), status=200)
        else:
            return HttpResponse("Bad syntax", status=400)
    else:
        return HttpResponse(status=404)
예제 #2
0
 def put(self, request, id):
     post = self.get_post(id)
     serializer = PostSerializer(instance=post, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response({'error': serializer.errors})
예제 #3
0
 def post(self, request):
     serializer = PostSerializer(data=request.data)
     print(request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #4
0
 def post(self, request):
     serialized = PostSerializer(data=request.data)
     if serialized.is_valid(raise_exception=True):
         serialized.save()
         response = {"data": serialized.data}
         return Response(response, status=201)
     return Response({"message": "Error - not created"}, status=400)
예제 #5
0
 def put(self, request, user_id, pid, format=None):
     post = self.get_objects(user_id, pid)
     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)
예제 #6
0
    def post(self, request):
        data = JSONParser().parse(request)
        serialized = PostSerializer(data=data)

        if serialized.is_valid():
            serialized.save()
            return JsonResponse(serialized.data, status=status.HTTP_201_CREATED)
예제 #7
0
def api_create_blog_view(request):
    account = User.objects.get(pk=1)
    post = Post(author=account)

    if request.method == 'POST':
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# User views
# @api_view(['POST'])
# def api_registration_view(request):
#     if request.method == 'POST':
#         serializer = RegistrationSerializer(data=request.data)
#         data = {}
#         if serializer.is_valid():
#             user = serializer.save()
#             data['response'] = 'successfully registered a new user'
#             data['email'] = user.email
#             data['username'] = user.username
#         else:
#             data = serializer.errors
#         return Response(data)
    def put(self, request, pk, format=None):
        data = request.data

        # ensure user is authenticated
        if (not request.user.is_authenticated()):
            return Response({'message':'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            post = Post.objects.get(id=pk)
        except Post.DoesNotExist as e:
            return Response({"message":"Post does not exist"}, status=status.HTTP_404_NOT_FOUND)

        # only allow author of the post to modify it
        try:
            loggedInAuthor = Author.objects.get(user=request.user)
        except Author.DoesNotExist as e:
            return Response({"message":"Author does not exist"}, status=status.HTTP_401_UNAUTHORIZED)

        # only allow author of the post to modify it
        if loggedInAuthor != post.author:
            return Response({"message": "User is not the author of this post & is not allowed to update this post"}, status=status.HTTP_403_FORBIDDEN)


        # else logged in user is the author of the post
        serializer = PostSerializer(post, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #9
0
def get_all_posts(request):
    """
        Retorna um json com todos os post cadastrados
    """

    response = {
        "status": "failure",
    }

    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        response = {
            "status": "success",
            "shows": serializer.data,
        }
        return Response(response)

    elif request.method == 'POST':
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = {
                "status": "success",
                "shows": serializer.data,
            }
            return Response(response, status=status.HTTP_201_CREATED)
        response = {
            "status": "failure",
            "errors": serializer.errors,
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)

    return Response(response)
예제 #10
0
    def post(self, request):  #Allows user to create a new post
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(
                owner=request.user)  #Turns data into actual book object
            return Response(serializer.data, status=201)

        return Response(serializer.errors, status=400)
예제 #11
0
def post_list(request):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)
    if request.method == 'POST':
        serializer = PostSerializer(data=request.DATA)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
    def put(self, request, id):
        post = self.get_object(id)
        serializer = PostSerializer(post, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #13
0
 def post(self, request, pk):
     post = self.get_object(pk)
     post.like_count += 1
     request.data['title'] = post.title
     serializer = PostSerializer(instance=post, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors)
예제 #14
0
 def post(self, request, id):
     category = self.get_category(id)
     profile = Profile.objects.get(user=self.request.user)
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save(category=category, author_id=profile.id)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response({'error': serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
예제 #15
0
 def update(self, request, pk=None):
     try:
         item = Post.objects.get(pk=pk)
     except Post.DoesNotExist:
         return Response(status=404)
     serializer = PostSerializer(item, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=400)
예제 #16
0
 def put(self, request, id, format=None):
     post = self.get_object(id)
     if post == False:
         return JsonResponse({'msg': 'Post was not found'}, status=404)
     request.data['created_at'] = post.created_at
     serializer = PostSerializer(post, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return JsonResponse(serializer.data, status=204)
     return JsonResponse(serializer.errors, status=400)
예제 #17
0
 def post(self, request, pk=None):
     if pk:
         return Response({'error': 'Unhandled Method !!'}, status=403)
     # there is no need for us to do parsing as APIView does it for us !! Thanks APIView.....
     data = request.data
     post = PostSerializer(data=data)
     if post.is_valid():
         post.save(user=request.user)
         return Response(post.data, status=201)
     return Response(post.errors, status=400)
예제 #18
0
    def update(self, request, pk=None):
        post = PostModel.objects.get(id=pk)
        data = JSONParser().parse(request)
        serialized = PostSerializer(post, data=data)

        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data)

        return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #19
0
    def put(self, request, id):
        post = self.get_object(id)
        data = JSONParser().parse(request)
        serialized = PostSerializer(post, data=data)

        if serialized.is_valid():
            serialized.save()
            return JsonResponse(serialized.data, status=status.HTTP_202_ACCEPTED)

        return JsonResponse(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #20
0
def addPost(request):
    
    if request.method == "POST":
        data = JSONParser().parse(request)
        serialized = PostSerializer(data=data)

        if serialized.is_valid():
            serialized.save()
            return JsonResponse(serialized.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #21
0
 def put(self, request, id, format=None):
     try:
         item = Post.objects.get(pk=id)
     except Post.DoesNotExist:
         return Response(status=404)
     serializer = PostSerializer(item, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=400)
예제 #22
0
파일: views.py 프로젝트: pandye/ecommerce
def post_list(request, format=None):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #23
0
def test_invalid_post_serializer(add_thread, add_forum, add_user):
    forum = add_forum(title='General Forum', description='A general forum')
    user = add_user(username='******', email='*****@*****.**', password='******')
    thread = add_thread(title='A new thread', text='text in the thread', forum=forum, user=user)
    invalid_serializer_data = {
        'text': 'A General Forum',
        'forum': forum.id,
        'user': user.id,
    }
    serializer = PostSerializer(data=invalid_serializer_data)
    assert not serializer.is_valid()
    assert serializer.validated_data == {}
    assert serializer.errors == {"thread": ["This field is required."]}
예제 #24
0
 def put(self, request, pk=None):
     if not pk:
         return Response({'error': 'Unhandled Method !!'}, status=403)
     try:
         post = Post.objects.get(pk=pk)
     except ObjectDoesNotExist:
         return JsonResponse({'error': 'Post not found with {}'.format(pk)},
                             status=404)
     data = request.data
     post = PostSerializer(post, data=data)
     if post.is_valid():
         post.save(user=request.user)
         return Response(post.data)
예제 #25
0
 def get(self, request, pk=None):
     posts = Post.objects.all()
     if pk:
         try:
             post = posts.get(pk=pk)
         except ObjectDoesNotExist:
             return Response({'error': 'Post not found with {}'.format(pk)},
                             status=404)
         post = PostSerializer(post)
         return Response(post.data)
     posts = Post.objects.all()
     posts = PostSerializer(posts, many=True)
     return Response(posts.data)
예제 #26
0
    def get(self, request, post_id):
        is_local = is_local_request(request)
        response_object = {"query": "getPost", "post": None}
        #first we check to see if the post with the id exists
        try:
            post = Post.objects.get(pk=post_id)  # pylint: disable=maybe-no-member
        except:
            return Response(response_object, status=status.HTTP_404_NOT_FOUND)

        if not is_sharePosts(is_local, request.user):
            return Response(response_object, status=403)

        if not is_shareImgs(is_local, request.user):
            if post.contentType == 'image/png;base64' or post.contentType == 'image/jpeg;base64':
                return Response(status=403)

        #if the posts visibility is set
        #to PUBLIC, we are ok to return it
        if (post.visibility == "PUBLIC"):
            serializer = PostSerializer(post)
            response_object = serializer.data
            return Response(response_object, status=status.HTTP_200_OK)

        #otherwise, the other privacy settings
        #require that an author be logged in

        # lets check if an author is logged in first
        # here, author has to login in order to view the posts,
        try:
            author = get_request_author(is_local, request)
        except:
            return Response(response_object, status=status.HTTP_403_FORBIDDEN)

        #check if its the currently authenticated
        #users post
        if (author.id == post.postauthor.id):
            serializer = PostSerializer(post)
            response_object = serializer.data
            return Response(response_object, status=status.HTTP_200_OK)

        check_permissions = CheckPermissions(author, post)

        # if current author has no permission:
        if (not check_permissions[1]):
            return Response(response_object, status=status.HTTP_403_FORBIDDEN)

        # current user has permission
        serializer = PostSerializer(post)
        response_object = serializer.data
        return Response(response_object, status=status.HTTP_200_OK)
예제 #27
0
 def post(self, request):
     # POST: Create a post
     curAuthor = Author.objects.get(id=request.user.id)
     origin = request.scheme + "://" + request.get_host() + "/"
     serializer = PostSerializer(data=request.data,
                                 context={
                                     'author': curAuthor,
                                     'origin': origin
                                 })
     if serializer.is_valid():
         serializer.save()
         #Todo: response success message on json format
         return Response()
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #28
0
def api_update_blog_view(request, pk):
    try:
        post = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'PUT':
        serializer = PostSerializer(post, data=request.data)
        data = {}
        if serializer.is_valid():
            serializer.save()
            data['success'] = 'update successful'
            return Response(data=data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #29
0
def json_to_posts(json, node):
    posts = json["posts"]
    out = []
    for p in posts:
        guid = p.get('guid', None)
        if guid is None:
            # Bad json
            continue

        post = Post.objects.filter(guid=guid).first()
        # Try except here because if they pass us a post
        # from a host we don't know then we error out and 
        # do nothing, realistically we should just pass over
        # that post... I know Mark doesn't like this but meh
        # trying to get thigns to work...
        try:
            if post is None:
                # create post
                serializer = PostSerializer(data=p)
                serializer.is_valid(raise_exception=True)
                post = serializer.save(node=node)
            else:
                # update post
                serializer = PostSerializer(post, data=p)
                serializer.is_valid(raise_exception=True)
                post = serializer.save(node=node)
                out.append(post)
        except Exception as e:
            logger.log("Error serializing post: "+ str(e) + "\r\n Post JSON:" + str(p))
            continue
    return out
예제 #30
0
def test_valid_post_serializer(add_thread, add_forum, add_user):
    forum = add_forum(title='General Forum', description='A general forum')
    user = add_user(username='******', email='*****@*****.**', password='******')
    thread = add_thread(title='A new thread', text='text in the thread', forum=forum, user=user)
    valid_serializer_data = {
        'text': 'A General Forum',
        'thread': thread.id,
        'forum': forum.id,
        'user': user.id,
    }
    serializer = PostSerializer(data=valid_serializer_data)

    assert serializer.is_valid()
    assert serializer.errors == {}
예제 #31
0
 def patch(self, request, pk):
     post_obj = self.get_post(pk)
     serialized = PostSerializer(
         post_obj,
         data=request.data,
         partial=True,
     )
     if serialized.is_valid(raise_exception=True):
         serialized.save()
         response = {
             "data": serialized.data,
             "message": "All good, updated",
         }
         return Response(response, status=200)
     return Response({"message": "Error - not updated"}, status=400)
예제 #32
0
파일: views.py 프로젝트: pandye/ecommerce
def post_single(request, id, format=None):
    post = get_object_or_404(Post, id=id)
    if request.method == 'GET':
        serializer = PostSerializer(post)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = PostSerializer(post, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        post.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
예제 #33
0
파일: posts.py 프로젝트: rokn/kanq
    def create(self, request, *args, **kwargs):  # Upload image to server if needed and create post
        data = request.data.copy()
        posts_count = Post.objects.filter(topic_id=data['topic_id'], creator=data['creator_id']).count()
        if posts_count >= MAX_POSTS_ALLOWED:
            return Response(status=status.HTTP_403_FORBIDDEN)

        if data['topic_id'] is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        topic = Topic.objects.get(pk=data['topic_id'])
        if not topic.is_active():
            return Response(status=status.HTTP_403_FORBIDDEN)

        images_dir = './images/'
        image_name = '{}_{}'.format(request.data['creator_id'], timezone.now().strftime("%Y_%m_%d_%H_%M_%S"))
        image_extension = request.data['extension']
        if '.' not in image_extension:
            image_extension = '.' + image_extension

        full_path = '{}{}{}'.format(images_dir, image_name, image_extension)

        if not os.path.exists(images_dir):
            os.makedirs(images_dir)

        image = data['image']
        decoded = base64.b64decode(image)
        with open(full_path, "wb") as fh:
            fh.write(decoded)
        fh.close()

        image = Image.objects.create(uri=full_path)
        post = Post.objects.create(description=data['description'], title=data['title'],
                                   creator_id=data['creator_id'], topic_id=data['topic_id'], image_id=image.id)
        serializer = PostSerializer(instance=post)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
예제 #34
0
def wish_detail(request, pk=None):
    if request.method == 'POST':
        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)
    else:
        try:
            post = Post.objects.get(pk=pk)
        except Post.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if request.method == 'DELETE':
            post.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
예제 #35
0
    def get(self, request, pk):
        post = Post.objects.filter(id=pk)

        serializer = PostSerializer(post, many=True)

        return Response({"response": serializer.data},
                        status=status.HTTP_200_OK)
예제 #36
0
 def get(self, request, id, format=None):
     try:
         item = Post.objects.get(pk=id)
         serializer = PostSerializer(item)
         return Response(serializer.data)
     except Post.DoesNotExist:
         return Response(status=404)
예제 #37
0
    def get(self, request):
        is_local = is_local_request(request)

        response_object = {
            "query": "getPosts",
            "count": None,
            "size": None,
            "next": None,
            "previous": None,
            "posts": None
        }

        if not is_sharePosts(is_local, request.user):
            return Response(status=403)

        request_url = request.build_absolute_uri("/").strip("/")
        previous_page = None

        #start off by  getting the
        #page and size from the query string
        try:
            page = int(request.GET.get("page", ""))
        except:
            page = ""
        try:
            size = int(request.GET.get("size", ""))
        except:
            size = ""

        posts = Post.objects.filter(visibility="PUBLIC",
                                    unlisted=False).order_by('published')  # pylint: disable=maybe-no-member

        if not is_shareImgs(is_local, request.user):
            posts = posts.exclude(
                Q(contentType='image/png;base64')
                | Q(contentType='image/jpeg;base64'))

        count = posts.count()

        if (page and size):
            paginator = Paginator(posts, size)

            if (page > paginator.num_pages):
                posts = None
            else:
                posts = paginator.get_page(page)

            response_object["size"] = size
            if (page > 1):
                previous_page = request_url + "/posts?page={}&size={}".format(
                    page - 1, size)
            next_page = request_url + "/posts?page={}&size={}".format(
                page + 1, size)
            response_object["next"] = next_page
            response_object["previous"] = previous_page

        serializer = PostSerializer(posts, many=True)
        response_object["posts"] = serializer.data
        response_object["count"] = count
        return Response(response_object, status=status.HTTP_200_OK)
예제 #38
0
파일: wiki_api.py 프로젝트: amoyx/OpsManage
def archive_detail(request, id,format=None):
    try:
        snippet = Post.objects.get(id=id)
    except Post.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
 
    if request.method == 'GET':
        serializer = PostSerializer(snippet)
        return Response(serializer.data)
 
    elif request.method == 'PUT':
        serializer = PostSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
     
    elif request.method == 'DELETE':
        if not request.user.has_perm('OpsManage.can_delete_wiki_post'):
            return Response(status=status.HTTP_403_FORBIDDEN)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)      
    def post(self, request, post_pk=None, format=None):
        # ensure user is authenticated
        if (not request.user.is_authenticated()):
            return Response({'message':'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED)

        data = request.data

        '''
        Gets the author from the request
        '''
        try:
            author = Author.objects.get(user=request.user)
        except Author.DoesNotExist as e:
            return Response({"message":"Author does not exist / is not a local author"}, status=status.HTTP_400_BAD_REQUEST)

        # If its a remote node - not allowed to make posts
        if request.get_host() not in author.host:
            return Response({"message":"Only local authors can make posts"}, status=status.HTTP_403_FORBIDDEN)


        statusCode = status.HTTP_201_CREATED
        serializer = PostSerializer(data=data)

        '''
        Handles : EDIT Posts via POST method
        '''
        if post_pk != None:
            try:
                post = Post.objects.get(id=post_pk)
            except Post.DoesNotExist as e:
                return Response({"message": "Post does not exist"}, status=status.HTTP_404_NOT_FOUND)


            # only allow author of the post to modify it
            if author != post.author:
                return Response({"message":"Only the author of this post can make changes to it"}, status=status.HTTP_403_FORBIDDEN)

            statusCode = status.HTTP_200_OK
            serializer = PostSerializer(post, data=data)



        if serializer.is_valid():
            print "DEBUG : API - views.py - PostList"
            serializer.validated_data["author"] = author
            serializer.validated_data["published"] = timezone.now()
            serializer.save()
            return Response(serializer.data, status=statusCode)

        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #40
0
 def create(self, request):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=201)
     return Response(serializer.errors, status=400)