Exemple #1
0
    def post(self, request, *args, **kwargs):

        validation_result = post_validate(request)

        if validation_result is True:
            # invalidate the nonce, so this form cannot be
            # resubmitted with the current id
            request.session['nonce'] = False
            '''
            If there is a thumbnail, and it was sent as part of an
            application/json payload, then we need to unpack a thumbnail
            object payload and convert it to a Python ContentFile payload
            instead. We use a try/catch because the optional nature means
            we need to check using "if hasattr(request.data,'thumbnail'):"
            as we as "if request.data['thumnail']" and these are pretty
            much mutually exclusive patterns. A try/pass make far more sense.
            '''

            try:
                thumbnail = request.data['thumbnail']
                # do we actually need to repack as ContentFile?
                if thumbnail['name'] and thumbnail['base64']:
                    name = thumbnail['name']
                    encdata = thumbnail['base64']
                    proxy = ContentFile(base64.b64decode(encdata), name=name)
                    request.data['thumbnail'] = proxy
            except:
                pass

            serializer = EntrySerializer(data=request.data)
            if serializer.is_valid():
                user = request.user
                # ensure that the published_by is always the user doing
                # the posting, and set 'featured' to false.
                #
                # see https://github.com/mozilla/network-pulse-api/issues/83
                moderation_state = ModerationState.objects.get(name='Pending')

                if (is_staff_address(request.user.email)):
                    moderation_state = ModerationState.objects.get(
                        name='Approved')

                savedEntry = serializer.save(published_by=user,
                                             featured=False,
                                             moderation_state=moderation_state)
                return Response({'status': 'submitted', 'id': savedEntry.id})
            else:
                return Response(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response("post validation failed",
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
    def test_profile_data_serialization(self):
        """
        Make sure profiles have "created_entries" array
        """
        user = self.users_with_profiles[0]
        profile = user.profile
        location = "Springfield, IL"
        profile.location = location
        profile.save()

        id = profile.id
        response = self.client.get(reverse('profile', kwargs={'pk': id}))
        entriesjson = json.loads(str(response.content, 'utf-8'))

        self.assertEqual(entriesjson['location'], location)

        created_entries = []
        entry_creators = OrderedCreatorRecord.objects.filter(
            creator__profile=id).order_by('-id')

        created_entries = [
            EntrySerializer(x.entry).data for x in entry_creators
        ]
        self.assertEqual(entriesjson['profile_id'], id)
        self.assertEqual(entriesjson['created_entries'], created_entries)

        # make sure extended profile data does not show
        self.assertEqual('program_type' in entriesjson, False)
 def get_created_entries(self, instance):
     entry_creator_records = OrderedCreatorRecord.objects.filter(
         creator__profile=instance)
     return [
         EntrySerializer(x.entry).data for x in entry_creator_records
         if x.entry.is_approved()
     ]
    def get_published_entries(self, instance):
        user = instance.user

        return EntrySerializer(
            user.entries.public(),
            context=self.context,
            many=True,
        ).data if user else []
    def get_published_entries(self, instance):
        user = instance.user

        return EntrySerializer(
            user.entries.public().with_related().order_by('-id'),
            context=self.context,
            many=True,
        ).data if user else []
    def test_profile_data_serialization(self):
        """
        Make sure profiles have "created_entries" array
        """
        id = self.users_with_profiles[0].id
        response = self.client.get(reverse('profile', kwargs={'pk': id}))
        entriesjson = json.loads(str(response.content, 'utf-8'))

        created_entries = []
        entry_creators = OrderedCreatorRecord.objects.filter(
            creator__profile=self.users_with_profiles[0].id)

        created_entries = [
            EntrySerializer(x.entry).data for x in entry_creators
        ]

        self.assertEqual(entriesjson['created_entries'], created_entries)
    def test_entry_serializer(self):
        """
        Make sure that the entry serializer contains all the custom data needed.
        Useful test to make sure our custom fields are tested and not
        removed during API changes
        """

        entries = self.entries
        serialized_entries = EntrySerializer(entries, many=True).data

        for i in range(len(serialized_entries)):
            entry = entries[i]
            serialized_entry = dict(serialized_entries[i])
            self.assertIn('related_creators', serialized_entry)
            related_creators = serialized_entry['related_creators']
            # Make sure that the number of serialized creators matches the
            # number of creators for that entry in the db
            db_entry_creator_count = OrderedCreatorRecord.objects.filter(
                entry=entry).count()
            self.assertEqual(len(related_creators), db_entry_creator_count)
    def post(self, request, *args, **kwargs):
        request_data = request.data

        validation_result = post_validate(request)

        if validation_result is True:
            # invalidate the nonce, so this form cannot be
            # resubmitted with the current id
            request.session['nonce'] = False
            '''
            If there is a thumbnail, and it was sent as part of an
            application/json payload, then we need to unpack a thumbnail
            object payload and convert it to a Python ContentFile payload
            instead. We use a try/catch because the optional nature means
            we need to check using "if hasattr(request.data,'thumbnail'):"
            as we as "if request.data['thumnail']" and these are pretty
            much mutually exclusive patterns. A try/pass make far more sense.
            '''

            try:
                thumbnail = request_data['thumbnail']
                # do we actually need to repack as ContentFile?
                if thumbnail['name'] and thumbnail['base64']:
                    name = thumbnail['name']
                    encdata = thumbnail['base64']
                    proxy = ContentFile(base64.b64decode(encdata), name=name)
                    request_data['thumbnail'] = proxy
            except:
                pass

            # we need to split out creators, because it's a many-to-many
            # relation with a Through class, so that needs manual labour:
            creator_data = request_data.pop('creators', [])

            # we also want to make sure that tags are properly split
            # on commas, in case we get e.g. ['a', 'b' 'c,d']
            if 'tags' in request_data:
                tags = request_data['tags']
                filtered_tags = []
                for tag in tags:
                    if ',' in tag:
                        filtered_tags = filtered_tags + tag.split(',')
                    else:
                        filtered_tags.append(tag)
                request_data['tags'] = filtered_tags

            serializer = EntrySerializer(
                data=request_data,
                context={'request': request},
            )
            if serializer.is_valid():
                user = request.user
                # ensure that the published_by is always the user doing
                # the posting, and set 'featured' to false.
                #
                # see https://github.com/mozilla/network-pulse-api/issues/83
                moderation_state = ModerationState.objects.get(name='Pending')

                if (is_staff_address(request.user.email)):
                    moderation_state = ModerationState.objects.get(
                        name='Approved')

                # save the entry
                saved_entry = serializer.save(
                    published_by=user,
                    featured=False,
                    moderation_state=moderation_state)

                # QUEUED FOR DEPRECATION: Use the `related_creators` property instead.
                # See https://github.com/mozilla/network-pulse-api/issues/241
                if len(creator_data) > 0:
                    for creator_name in creator_data:
                        (creator,
                         _) = Creator.objects.get_or_create(name=creator_name)

                        OrderedCreatorRecord.objects.create(entry=saved_entry,
                                                            creator=creator)

                return Response({'status': 'submitted', 'id': saved_entry.id})
            else:
                return Response(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(
                "post validation failed - {}".format(validation_result),
                status=status.HTTP_400_BAD_REQUEST)
Exemple #9
0
    def post(self, request, *args, **kwargs):

        request_data = request.data
        validation_result = post_validate(request)

        if validation_result is True:
            # invalidate the nonce, so this form cannot be
            # resubmitted with the current id
            request.session['nonce'] = False

            '''
            If there is a thumbnail, and it was sent as part of an
            application/json payload, then we need to unpack a thumbnail
            object payload and convert it to a Python ContentFile payload
            instead. We use a try/catch because the optional nature means
            we need to check using "if hasattr(request.data,'thumbnail'):"
            as we as "if request.data['thumnail']" and these are pretty
            much mutually exclusive patterns. A try/pass make far more sense.
            '''

            try:
                thumbnail = request_data['thumbnail']
                # do we actually need to repack as ContentFile?
                if thumbnail['name'] and thumbnail['base64']:
                    name = thumbnail['name']
                    encdata = thumbnail['base64']
                    proxy = ContentFile(base64.b64decode(encdata), name=name)
                    request_data['thumbnail'] = proxy
            except:
                pass

            # we need to split out creators, because it's a many-to-many
            # relation with a Through class, so that needs manual labour:
            creator_data = request_data.pop('creators', None)

            serializer = EntrySerializer(data=request_data)
            if serializer.is_valid():
                user = request.user
                # ensure that the published_by is always the user doing
                # the posting, and set 'featured' to false.
                #
                # see https://github.com/mozilla/network-pulse-api/issues/83
                moderation_state = ModerationState.objects.get(
                    name='Pending'
                )

                if (is_staff_address(request.user.email)):
                    moderation_state = ModerationState.objects.get(
                        name='Approved'
                    )

                # save the entry
                saved_entry = serializer.save(
                    published_by=user,
                    featured=False,
                    moderation_state=moderation_state
                )

                # create entry/creator intermediaries
                if creator_data is not None:
                    for creator_name in creator_data:
                        # TODO: update Creator model so that it can fall through
                        #       to a profile is the correct format to achieve this
                        #       is specified.
                        (creator, _) = Creator.objects.get_or_create(name=creator_name)

                        OrderedCreatorRecord.objects.create(
                            entry=saved_entry,
                            creator=creator
                        )

                return Response({'status': 'submitted', 'id': saved_entry.id})
            else:
                return Response(
                    serializer.errors,
                    status=status.HTTP_400_BAD_REQUEST
                )

        else:
            return Response(
                "post validation failed",
                status=status.HTTP_400_BAD_REQUEST
            )