Exemplo n.º 1
0
 def test_get_canonical_serializer_by_instance(self):
     dog = Dog.objects.create(name='Snoopy',
                              fur_color='black and white',
                              origin='')
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, instance=dog))
Exemplo n.º 2
0
    def test_unknown_resource(self):
        """Test case where polymorhpic relation pulls in an object for
        which there is no known canonical serializer.
        """

        zork = Zebra.objects.create(
            name='Zork',
            origin='San Francisco Zoo'
        )

        user = self.fixture.users[0]
        user.favorite_pet = zork
        user.save()

        self.assertIsNone(DynamicRouter.get_canonical_serializer(Zebra))

        url = '/users/%s/?include[]=favorite_pet' % user.pk
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        content = json.loads(response.content.decode('utf-8'))
        self.assertTrue('user' in content)
        self.assertFalse('zebras' in content)  # Not sideloaded
        user_obj = content['user']
        self.assertTrue('favorite_pet' in user_obj)
        self.assertEqual('Zebra', user_obj['favorite_pet']['type'])
        self.assertEqual(zork.pk, user_obj['favorite_pet']['id'])
Exemplo n.º 3
0
    def serializer_class(self):
        """Get the class of the child serializer.

        Resolves string imports.
        """
        serializer_class = self._serializer_class
        if serializer_class is None:
            from dynamic_rest.routers import DynamicRouter
            serializer_class = DynamicRouter.get_canonical_serializer(
                None, model=get_related_model(self.model_field))

        if not isinstance(serializer_class, six.string_types):
            return serializer_class

        parts = serializer_class.split('.')
        module_path = '.'.join(parts[:-1])
        if not module_path:
            if getattr(self, 'parent', None) is None:
                raise Exception(
                    "Can not load serializer '%s'" % serializer_class +
                    ' before binding or without specifying full path')

            # try the module of the parent class
            module_path = self.parent.__module__

        module = importlib.import_module(module_path)
        serializer_class = getattr(module, parts[-1])

        self._serializer_class = serializer_class
        return serializer_class
Exemplo n.º 4
0
 def test_get_canonical_serializer_by_instance(self):
     dog = Dog.objects.create(
         name='Snoopy',
         fur_color='black and white',
         origin=''
     )
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, instance=dog)
     )
Exemplo n.º 5
0
    def to_internal_value(self, data):
        model_name = data.get('type', None)
        model_id = data.get('id', None)
        if model_name and model_id:
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None, resource_name=model_name)
            if serializer_class:
                model = serializer_class.get_model()
                return model.objects.get(id=model_id) if model else None

        return None
Exemplo n.º 6
0
    def to_internal_value(self, data):
        model_name = data.get('type', None)
        model_id = data.get('id', None)
        if model_name and model_id:
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None,
                resource_name=model_name
            )
            if serializer_class:
                model = serializer_class.get_model()
                return model.objects.get(id=model_id) if model else None

        return None
Exemplo n.º 7
0
    def to_representation(self, instance):
        try:
            # Find serializer for the instance
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None,
                instance=instance
            )
            if not serializer_class:
                # Can't find canonical serializer! For now, just return
                # object name and ID, and hope the client knows what to do
                # with it.
                return self.get_pk_object(
                    instance._meta.object_name,
                    instance.pk
                )

            # We want the pk to be represented as an object with type,
            # rather than just the ID.
            pk_value = self.get_pk_object(
                serializer_class.get_name(),
                instance.pk
            )
            if self.id_only():
                return pk_value

            # Serialize the object. Note that request_fields is set, but
            # field inclusion/exclusion is disallowed via check in bind()
            r = serializer_class(
                dynamic=True,
                request_fields=self.request_fields,
                context=self.context,
                embed=self.embed
            ).to_representation(
                instance
            )

            # Pass pk object that contains type and ID to TaggedDict object
            # so that Processor can use it when the field gets sideloaded.
            if isinstance(r, TaggedDict):
                r.pk_value = pk_value
            return r
        except:
            # This feature should be considered to be in Beta so don't break
            # if anything unexpected happens.
            # TODO: Remove once we have more confidence.
            traceback.print_exc()
            return None
Exemplo n.º 8
0
    def to_representation(self, instance):
        try:
            # Find serializer for the instance
            serializer_class = DynamicRouter.get_canonical_serializer(
                resource_key=None,
                instance=instance
            )
            if not serializer_class:
                # Can't find canonical serializer! For now, just return
                # object name and ID, and hope the client knows what to do
                # with it.
                return self.get_pk_object(
                    instance._meta.object_name,
                    instance.pk
                )

            # We want the pk to be represented as an object with type,
            # rather than just the ID.
            pk_value = self.get_pk_object(
                serializer_class.get_name(),
                instance.pk
            )
            if self.id_only():
                return pk_value

            # Serialize the object. Note that request_fields is set, but
            # field inclusion/exclusion is disallowed via check in bind()
            r = serializer_class(
                dynamic=True,
                request_fields=self.request_fields,
                context=self.context,
                embed=self.embed
            ).to_representation(
                instance
            )

            # Pass pk object that contains type and ID to TaggedDict object
            # so that Processor can use it when the field gets sideloaded.
            if isinstance(r, TaggedDict):
                r.pk_value = pk_value
            return r
        except:
            # This feature should be considered to be in Beta so don't break
            # if anything unexpected happens.
            # TODO: Remove once we have more confidence.
            traceback.print_exc()
            return None
Exemplo n.º 9
0
    def test_unknown_resource(self):
        """Test case where polymorhpic relation pulls in an object for
        which there is no known canonical serializer.
        """

        zork = Zebra.objects.create(name='Zork', origin='San Francisco Zoo')

        user = self.fixture.users[0]
        user.favorite_pet = zork
        user.save()

        self.assertIsNone(DynamicRouter.get_canonical_serializer(Zebra))

        url = '/users/%s/?include[]=favorite_pet' % user.pk
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)
        content = json.loads(response.content.decode('utf-8'))
        self.assertTrue('user' in content)
        self.assertFalse('zebras' in content)  # Not sideloaded
        user_obj = content['user']
        self.assertTrue('favorite_pet' in user_obj)
        self.assertEqual('Zebra', user_obj['favorite_pet']['type'])
        self.assertEqual(zork.pk, user_obj['favorite_pet']['id'])
Exemplo n.º 10
0
 def get_serializer_class_for_instance(self, instance):
     return DynamicRouter.get_canonical_serializer(
         resource_key=None,
         instance=instance
     )
Exemplo n.º 11
0
 def test_get_canonical_serializer_by_model(self):
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, model=Dog))
Exemplo n.º 12
0
 def test_get_canonical_serializer(self):
     rsrc_key = get_model_table(Dog)
     self.assertEqual(DogSerializer,
                      DynamicRouter.get_canonical_serializer(rsrc_key))
Exemplo n.º 13
0
 def get_serializer_class_for_instance(self, instance):
     from dynamic_rest.routers import DynamicRouter
     return DynamicRouter.get_canonical_serializer(resource_key=None,
                                                   instance=instance)
Exemplo n.º 14
0
 def test_get_canonical_serializer_by_model(self):
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(None, model=Dog)
     )
Exemplo n.º 15
0
 def test_get_canonical_serializer(self):
     rsrc_key = get_model_table(Dog)
     self.assertEqual(
         DogSerializer,
         DynamicRouter.get_canonical_serializer(rsrc_key)
     )