Exemple #1
0
    def put(self, request, tag_slug, *args, **kwargs):
        """
        Return the credential information for this tag
        """
        user = request.user
        tag = CoreTag.objects.get(name__iexact=tag_slug)
        if not user.is_staff and user != tag.user:
            return Response([
                'Only the tag creator can update a tag.' +
                'Contact support if you need to change ' +
                'a tag that is not yours.'
            ],
                            status=status.HTTP_400_BAD_REQUEST)
        #Allowed to update tags..
        data = request.DATA.copy()
        if tag.user:
            data['user'] = tag.user.id
        else:
            data['user'] = user.id

        # Tag names are immutable
        data['name'] = tag.name
        serializer = TagSerializer(tag, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
    def post(self, request, provider_uuid, identity_uuid, instance_id,
             *args, **kwargs):
        """Create a new tag resource
        Params:name -- Name of the new Tag
        Returns: 
        Status Code: 201 Body: A new Tag object
        Status Code: 400 Body: Errors (Duplicate/Invalid Name)
        """
        user = request.user
        data = request.DATA.copy()
        if 'name' not in data:
            return Response("Missing 'name' in POST data",
                    status=status.HTTP_400_BAD_REQUEST)

        core_instance = get_core_instance(request, provider_uuid, identity_uuid, instance_id)
        if not core_instance:
            instance_not_found(instance_id)

        created = False
        same_name_tags = CoreTag.objects.filter(name__iexact=data['name'])
        if same_name_tags:
            add_tag = same_name_tags[0]
        else:
            data['user'] = user.username
            data['name'] = data['name'].lower()
            #description is optional
            serializer = TagSerializer(data=data)
            if not serializer.is_valid():
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            serializer.save()
            add_tag = serializer.object
            created = True
        core_instance.tags.add(add_tag)
        return Response(status=status.HTTP_204_NO_CONTENT)
    def post(self, request, provider_id, identity_id, instance_id,  *args, **kwargs):
        """Create a new tag resource
        Params:name -- Name of the new Tag
        Returns: 
        Status Code: 201 Body: A new Tag object
        Status Code: 400 Body: Errors (Duplicate/Invalid Name)
        """
        user = request.user
        data = request.DATA.copy()
        if 'name' not in data:
            return Response("Missing 'name' in POST data",
                    status=status.HTTP_400_BAD_REQUEST)

        core_instance = get_core_instance(request, provider_id, identity_id, instance_id)
        if not core_instance:
            instance_not_found(instance_id)

        created = False
        same_name_tags = CoreTag.objects.filter(name__iexact=data['name'])
        if same_name_tags:
            add_tag = same_name_tags[0]
        else:
            data['user'] = user.username
            data['name'] = data['name'].lower()
            #description is optional
            serializer = TagSerializer(data=data)
            if not serializer.is_valid():
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            serializer.save()
            add_tag = serializer.object
            created = True
        core_instance.tags.add(add_tag)
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #4
0
    def put(self, request, tag_slug, *args, **kwargs):
        """
        Return the credential information for this tag
        """
        user = request.user
        tag = CoreTag.objects.get(name__iexact=tag_slug)
        if not user.is_staff and user != tag.user:
            return Response([
                'Only the tag creator can update a tag.'
                + 'Contact support if you need to change '
                + 'a tag that is not yours.'],
                status=status.HTTP_400_BAD_REQUEST)
        #Allowed to update tags..
        data = request.DATA.copy()
        if tag.user:
            data['user'] = tag.user.id
        else:
            data['user'] = user.id

        # Tag names are immutable
        data['name'] = tag.name
        serializer = TagSerializer(tag, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #5
0
 def test_add_tags(self):
     tag = "Centos"
     data = {"name": tag}
     t = TagSerializer(data=data)
     self.assertTrue(t.is_valid())
     t.save()
     ts = Tag.objects.get(name=tag)
     self.assertTrue(ts.name == tag)
Exemple #6
0
def tag_list(request,format=None):
    if request.method == 'GET':      
        snippets = Tag.objects.all()
        serializer = TagSerializer(snippets, many=True)
        return Response(serializer.data)     
    elif request.method == 'POST':
        serializer = TagSerializer(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)
Exemple #7
0
 def put(self, request):
     profile = UserProfile.get(request)
     tag, created = Tag.objects.get_or_create(**request.data)
     count = profile.tags.count()
     profile.tags.add(ProfileTag.objects.create(tag=tag, rank=count))
     serializer = TagSerializer(profile.tags.list(), many=True)
     return Response(serializer.data)
Exemple #8
0
 def get(self, request, *args, **kwargs):
     """
     List all public tags.
     """
     tags = CoreTag.objects.all()
     serializer = TagSerializer(tags, many=True)
     return Response(serializer.data)
Exemple #9
0
    def post(self, request, *args, **kwargs):
        keywords = self.request.data.get('keywords')
        label = self.request.data.get('label')
        calendar_ids = self.request.query_params.get('calendar_ids')
        start = self.request.query_params.get('start')
        end = self.request.query_params.get('end')
        timezone = self.request.query_params.get('timezone')
        if not keywords or not label:
            return Response({'Missing field label or keywords'},
                            status=status.HTTP_400_BAD_REQUEST)

        tag = Tag()
        tag.user = self.request.user
        tag.keywords = keywords
        tag.label = label
        tag.save()

        context = {
            'start': start,
            'end': end,
            'calendar_ids': calendar_ids,
            'timezone': timezone
        }
        serializer = TagSerializer(tag, context=context)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Exemple #10
0
def tag_list(request):
    """
    List all tags (with the number of questions per tag)
    """
    tags = Tag.objects.all().order_by("name")

    serializer = TagSerializer(tags, many=True)
    return Response(serializer.data)
 def test_all_tags(self):
     tags = Tag.objects.all()
     tag_serializer = TagSerializer(tags[0])
     self.assertEqual(tag_serializer.data['id'], 1)
     self.assertEqual(tag_serializer.data['name'], "Foo")
     self.assertEqual(tag_serializer.data['slug'], "foo-slug")
     self.assertLess(
         datetime.strptime(tag_serializer.data['createdAt'],
                           '%Y-%m-%dT%H:%M:%S.%fZ'), datetime.now())
Exemple #12
0
 def post(self, request, *args, **kwargs):
     """
     Create a new tag resource
     """
     user = request.user
     data = request.DATA.copy()
     same_name_tags = CoreTag.objects.filter(name__iexact=data['name'])
     if same_name_tags:
         return Response(
             ['A tag with this name already exists: %s' % same_name_tags],
             status=status.HTTP_400_BAD_REQUEST)
     data['user'] = user.username
     data['name'] = data['name'].lower()
     serializer = TagSerializer(data=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)
Exemple #13
0
 def post(self, request, *args, **kwargs):
     """
     Create a new tag resource
     """
     user = request.user
     data = request.DATA.copy()
     same_name_tags = CoreTag.objects.filter(name__iexact=data['name'])
     if same_name_tags:
         return Response(['A tag with this name already exists: %s'
                          % same_name_tags],
                         status=status.HTTP_400_BAD_REQUEST)
     data['user'] = user.username
     data['name'] = data['name'].lower()
     serializer = TagSerializer(data=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)
Exemple #14
0
 def get(self, request, provider_uuid, identity_uuid, instance_id, *args, **kwargs):
     """
     List all public tags.
     """
     core_instance = get_core_instance(request, provider_uuid,
                                       identity_uuid, instance_id)
     if not core_instance:
         instance_not_found(instance_id)
     tags = core_instance.tags.all()
     serializer = TagSerializer(tags, many=True)
     return Response(serializer.data)
Exemple #15
0
 def get(self, request, tag_slug, *args, **kwargs):
     """
     Return the credential information for this tag
     """
     try:
         tag = CoreTag.objects.get(name__iexact=tag_slug)
     except CoreTag.DoesNotExist:
         return Response(['Tag does not exist'],
                         status=status.HTTP_404_NOT_FOUND)
     serializer = TagSerializer(tag)
     return Response(serializer.data)
Exemple #16
0
def tag_detail(request, id,format=None):
    try:
        snippet = Tag.objects.get(id=id)
    except Tag.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
 
    if request.method == 'GET':
        serializer = TagSerializer(snippet)
        return Response(serializer.data)
 
    elif request.method == 'PUT':
        serializer = TagSerializer(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_tag'):
            return Response(status=status.HTTP_403_FORBIDDEN)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Exemple #17
0
def tag_list(request, format=None):
    if request.method == 'GET':
        snippets = Tag.objects.all()
        serializer = TagSerializer(snippets, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = TagSerializer(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)
Exemple #18
0
 def get(self, request, provider_uuid, identity_uuid, instance_id,  tag_slug, *args, **kwargs):
     """
     Return the credential information for this tag
     """
     core_instance = get_core_instance(request, provider_uuid, identity_uuid, instance_id)
     if not core_instance:
         instance_not_found(instance_id)
     try:
         tag = core_instance.tags.get(name__iexact=tag_slug)
     except CoreTag.DoesNotExist:
         return Response(['Tag does not exist'],
                         status=status.HTTP_404_NOT_FOUND)
     serializer = TagSerializer(tag)
     return Response(serializer.data)
Exemple #19
0
    def update_tag(self, request, tag_slug, partial=False):
        user = request.user
        tag = CoreTag.objects.get(name__iexact=tag_slug)
        if not user.is_staff and user != tag.user:
            return Response([
                "Only the tag creator can update a tag."
                "Contact support if you need to change "
                "a tag that is not yours."],
                status=status.HTTP_400_BAD_REQUEST)
        # Allowed to update tags..
        data = request.DATA.copy()
        if tag.user:
            data['user'] = tag.user
        else:
            data['user'] = user

        # Tag names are immutable
        data['name'] = tag.name
        serializer = TagSerializer(tag, data=data, partial=partial)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #20
0
    def update_tag(self, request, tag_slug, partial=False):
        user = request.user
        tag = CoreTag.objects.get(name__iexact=tag_slug)
        if not user.is_staff and user != tag.user:
            return Response([
                'Only the tag creator can update a tag.' +
                'Contact support if you need to change ' +
                'a tag that is not yours.'
            ],
                            status=status.HTTP_400_BAD_REQUEST)
        # Allowed to update tags..
        data = request.DATA.copy()
        if tag.user:
            data['user'] = tag.user
        else:
            data['user'] = user

        # Tag names are immutable
        data['name'] = tag.name
        serializer = TagSerializer(tag, data=data, partial=partial)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #21
0
def tag_detail(request, id, format=None):
    try:
        snippet = Tag.objects.get(id=id)
    except Tag.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = TagSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = TagSerializer(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('wiki.wiki_can_delete_wiki_tag'):
            return Response(status=status.HTTP_403_FORBIDDEN)
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #22
0
    def create_category(id, title, slug, image, author_id):
        Category.objects.create(
            id=id, title=title, slug=slug, created=timezone.now(),
ls
    @staticmethod
    def create_article(id, title, slug, author_id, category_id, description="", content=""):
        Article.objects.create(
            id=id, title=title, slug=slug, created=timezone.now(), content=content,
            updated=timezone.now(), description=description, author_id=author_id, category_id=category_id)

    @staticmethod
    def create_tag(id, title, slug):
        Tag.objects.create(
            id=id, title=title, slug=slug, created=timezone.now(), updated=timezone.now())

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            username='******',
            password='******'
        )
        # add test data
        self.create_category(1, "food", "food", None,  self.user.pk)
        self.create_category(2, "sport", "sport", None,  self.user.pk)
        self.create_article(1, "About food", "about-food", self.user.pk, 1)
        self.create_article(2, "About sport", "about-sport", self.user.pk, 2)
        self.create_tag(2, "tag", "tag")


class CategoriesTest(BaseViewTest):

    def test_get_all_categories(self):
        """
        This test ensures that all categories added in the setUp method
        exist when we make a GET request to the endpoint
        """
        # hit the API endpoint
        response = self.client.get(
            reverse("endpoint:categories", kwargs={"version": "v1"})
        )
        # fetch the data from db
        expected = Category.objects.all()
        serialized = CategorySerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_category(self):
        response = self.client.get(
            reverse("endpoint:category", kwargs={"slug": "sport", "version": "v1"})
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)


class ArticlesTest(BaseViewTest):

    def test_get_all_articles(self):
        response = self.client.get(
            reverse("endpoint:articles", kwargs={"version": "v1"})
        )
        expected = Article.objects.all()
        serialized = ArticleSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_article(self):
        response = self.client.get(
            reverse("endpoint:article", kwargs={"slug": "about-sport", "version": "v1"})
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)


class TagsTest(BaseViewTest):

    def test_get_all_articles(self):
        response = self.client.get(
            reverse("endpoint:tags", kwargs={"version": "v1"})
        )
        expected = Tag.objects.all()
        serialized = TagSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Exemple #23
0
def random_tags(profile):
    from api.models import Tag
    from api.serializers import TagSerializer
    tags = random.sample(set(Tag.objects.filter(default=True)), random.randint(0, 3))
    profile.tags.update(TagSerializer(tags, many=True).data)
Exemple #24
0
 def post(self, request):
     profile = UserProfile.get(request)
     tags = profile.tags.update(request.data)
     serializer = TagSerializer(tags, many=True)
     return Response(serializer.data)
Exemple #25
0
 def get(self, request):
     profile = UserProfile.get(request)
     tags = Tag.search(profile=profile, **request.GET)
     serializer = TagSerializer(tags, many=True)
     return Response(serializer.data)