Пример #1
0
    def delete(self):
        assert self._get_pk_val() is not None, "%s object can't be deleted " \
                "because its %s attribute is set to None." \
                % (self._meta.object_name, self._meta.pk.attname)

        # Deletion in cascade should be done server side.
        resource = Resource(self.get_resource_url_detail(),
                            filters=ROA_FILTERS, **ROA_SSL_ARGS)

        logger.debug(u"""Deleting  : "%s" through %s""" % \
            (unicode(self), unicode(resource.uri)))

        # Add serializer content_type
        headers = get_roa_headers()
        headers.update(self.get_serializer_content_type())

        result = resource.delete(headers=headers, **ROA_CUSTOM_ARGS)
        if result.status_int in [200, 202, 204]:
            self.pk = None
Пример #2
0
 def _get_http_headers(self):
     return get_roa_headers()
Пример #3
0
    def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
                  force_update=False, using=None, update_fields=None):
        """
        Does the heavy-lifting involved in saving. Subclasses shouldn't need to
        override this method. It's separate from save() in order to hide the
        need for overrides of save() to pass around internal-only parameters
        ('raw', 'cls', and 'origin').
        """

        assert not (force_insert and force_update)

        record_exists = False

        if cls is None:
            cls = self.__class__
            meta = cls._meta
            if not meta.proxy:
                origin = cls
        else:
            meta = cls._meta

        if origin and not getattr(meta, "auto_created", False):
            signals.pre_save.send(sender=origin, instance=self, raw=raw)

        model_name = str(meta)

        # If we are in a raw save, save the object exactly as presented.
        # That means that we don't try to be smart about saving attributes
        # that might have come from the parent class - we just save the
        # attributes we have been given to the class we have been given.
        # We also go through this process to defer the save of proxy objects
        # to their actual underlying model.
        if not raw or meta.proxy:
            if meta.proxy:
                org = cls
            else:
                org = None
            for parent, field in meta.parents.items():
                # At this point, parent's primary key field may be unknown
                # (for example, from administration form which doesn't fill
                # this field). If so, fill it.
                if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
                    setattr(self, parent._meta.pk.attname, getattr(self, field.attname))

                self.save_base(cls=parent, origin=org, using=using)

                if field:
                    setattr(self, field.attname, self._get_pk_val(parent._meta))
            if meta.proxy:
                return

        if not meta.proxy:
            pk_val = self._get_pk_val(meta)
            pk_is_set = pk_val is not None

            get_args = {}
            get_args[ROA_ARGS_NAMES_MAPPING.get('FORMAT', 'format')] = ROA_FORMAT
            get_args.update(ROA_CUSTOM_ARGS)

            # Construct Json payload
            serializer = self.get_serializer(self)
            payload = self.get_renderer().render(serializer.data)

            # Add serializer content_type
            headers = get_roa_headers()
            headers.update(self.get_serializer_content_type())

            # check if resource use custom primary key
            if not meta.pk.attname in ['pk', 'id']:
                # consider it might be inserting so check it first
                # @todo: try to improve this block to check if custom pripary key is not None first
                resource = Resource(self.get_resource_url_detail(),
                                    filters=ROA_FILTERS, **ROA_SSL_ARGS)
                try:
                    response = resource.get(payload=None, headers=headers, **get_args)
                except ResourceNotFound:
                    # since such resource does not exist, it's actually creating
                    pk_is_set = False
                except RequestFailed:
                    pk_is_set = False

            if force_update or pk_is_set and not self.pk is None:
                record_exists = True
                resource = Resource(self.get_resource_url_detail(),
                                    filters=ROA_FILTERS, **ROA_SSL_ARGS)
                try:
                    logger.debug(u"""Modifying : "%s" through %s with payload "%s" and GET args "%s" """ % (
                                  force_unicode(self),
                                  force_unicode(resource.uri),
                                  force_unicode(payload),
                                  force_unicode(get_args)))
                    response = resource.put(payload=payload, headers=headers, **get_args)
                except RequestFailed as e:
                    raise ROAException(e)
            else:
                record_exists = False
                resource = Resource(self.get_resource_url_list(),
                                    filters=ROA_FILTERS, **ROA_SSL_ARGS)
                try:
                    logger.debug(u"""Creating  : "%s" through %s with payload "%s" and GET args "%s" """ % (
                                  force_unicode(self),
                                  force_unicode(resource.uri),
                                  force_unicode(payload),
                                  force_unicode(get_args)))
                    response = resource.post(payload=payload, headers=headers, **get_args)
                except RequestFailed as e:
                    raise ROAException(e)

            response = force_unicode(response.body_string()).encode(DEFAULT_CHARSET)

            data = self.get_parser().parse(StringIO(response))
            serializer = self.get_serializer(data=data)
            if not serializer.is_valid():
                raise ROAException(u'Invalid deserialization for %s model: %s' % (self, serializer.errors))
            try:
                self.pk = int(serializer.object.pk)
            except ValueError:
                self.pk = serializer.object.pk
            self = serializer.object

        if origin:
            signals.post_save.send(sender=origin, instance=self,
                created=(not record_exists), raw=raw)