Exemplo n.º 1
0
    def post_account(self, request, **kwargs):
        """
        Creates a new resource/object with the provided data.

        Calls ``obj_create`` with the provided data and returns a response
        with the new resource's location.

        If a new resource is created, return ``HttpCreated`` (201 Created).
        If ``Meta.always_return_data = True``, there will be a populated body
        of serialized data.
        """
        ### start copied from tasytpie ###
        if django.VERSION >= (1, 4):
            body = request.body
        else:
            body = request.raw_post_data
        deserialized = self.deserialize(request, body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        ## start custom code ##
        user_bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        # create user and account
        account_resource = AccountResource()
        address_resource = AddressResource()
        event_resource = EventResource()
        user_resource = UserResource()
        updated_user_bundle = user_resource.obj_create(user_bundle, **kwargs)

        # update the bundle with the user and account, then call the regular order code
        bundle.data['user'] = user_resource.get_resource_uri(updated_user_bundle.obj)
        bundle.data['account'] = account_resource.get_resource_uri(updated_user_bundle.obj.account_set.all()[0])
        updated_user_bundle.data['account'] = bundle.data['account']

        try:
            # create the event
            updated_event_bundle = event_resource.obj_create(updated_user_bundle, **kwargs)
            bundle.data['event'] = event_resource.get_resource_uri(updated_event_bundle.obj)
            updated_event_bundle.data['event'] = bundle.data['event']

            # create the location
            updated_location_bundle = address_resource.obj_create(updated_event_bundle, **kwargs)
        except:
            pass

        ## end custom code ##
        updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
        location = self.get_resource_uri(updated_bundle)

        if not self._meta.always_return_data:
            return http.HttpCreated(location=location)
        else:
            updated_bundle = self.full_dehydrate(updated_bundle)
            updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
            return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
    def patch_list(self, request, **kwargs):
        """
        Specialization of patch_list to do bulk target creation in a single RPC to job_scheduler (and
        consequently in a single command).
        """
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

        if "objects" not in deserialized:
            raise BadRequest("Invalid data sent.")

        if len(deserialized["objects"]) and 'put' not in self._meta.detail_allowed_methods:
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())

        # If any of the included targets is not a creation, then
        # skip to a normal PATCH instead of this special case one
        for target_data in deserialized['objects']:
            if 'id' in target_data or 'resource_uri' in target_data:
                super(TargetResource, self).patch_list(request, **kwargs)

        # Validate and prepare each target dict for consumption by job_scheduler
        for target_data in deserialized['objects']:
            data = self.alter_deserialized_detail_data(request, target_data)
            bundle = self.build_bundle(data=dict_strip_unicode_keys(data))
            bundle.request = request
            self.is_valid(bundle)

            target_data['content_type'] = ContentType.objects.get_for_model(KIND_TO_KLASS[target_data['kind']]).natural_key()

        targets, command = JobSchedulerClient.create_targets(deserialized['objects'])

        raise custom_response(self, request, http.HttpAccepted,
                              {'command': dehydrate_command(command),
                               'targets': [self.get_resource_uri(target) for target in targets]})
Exemplo n.º 3
0
Arquivo: api.py Projeto: golharam/TS
    def post_install(self, request, **kwargs):
        try:
            deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
            data=dict_strip_unicode_keys(deserialized)
        except UnsupportedFormat:
            return HttpBadRequest()

        # Assumes plugin_name is the same as last component of url. Questionable.
        url  = data.get("url","")
        filename = data.get("file",False)

        if url:
            plugin_name = os.path.splitext(os.path.basename(url))[0]
        elif filename:
            plugin_name = os.path.splitext(os.path.basename(filename))[0]
        else:
            # Must specify either url or filename
            return HttpBadRequest()

        # Create mock plugin object to pass details to downloadPlugin.
        # Do not save(), as we do not know if this is an install or upgrade yet.
        # And we don't know the version number.
        plugin = models.Plugin(name=plugin_name,
                               version="0",
                               date=datetime.datetime.now(),
                               active=False,
                               url=url,
                               status={'result': 'queued'},
                               )

        #now install the plugin
        tasks.downloadPlugin.delay(url, plugin, filename)

        # Task run async - return success
        return HttpAccepted()
Exemplo n.º 4
0
    def delete_detail(self, request, **kwargs):
        " Deleta um curso. "

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------

        course_id = course_id_decoder(kwargs['course_id_solaredx'])
        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = Bundle(data=dict_strip_unicode_keys(deserialized), 
            request=request)
        bundle.data['course_id'] = course_id
        validation = CleanedDataFormValidation(form_class=CourseDeleteForm)
        validation_errors = validation.is_valid(bundle)

        if validation_errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, validation_errors))        

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------

        course_delete(course_id)
        return http.HttpNoContent()
Exemplo n.º 5
0
    def post_list(self, request, **kwargs):
        """
        Exactly copied from https://github.com/toastdriven/django-tastypie/blob/v0.9.14/tastypie/resources.py#L1314
        (BSD licensed) and modified to catch Exception and not returning traceback
        """
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        try:
            updated_bundle = self.obj_create(
                bundle, **self.remove_api_resource_names(kwargs))
            location = self.get_resource_uri(updated_bundle)

            if not self._meta.always_return_data:
                return http.HttpCreated(location=location)
            else:
                updated_bundle = self.full_dehydrate(updated_bundle)
                updated_bundle = self.alter_detail_data_to_serialize(
                    request, updated_bundle)
                return self.create_response(request,
                                            updated_bundle,
                                            response_class=http.HttpCreated,
                                            location=location)
        except AssertionError as e:
            bundle.data['error_message'] = str(e)
            return self.create_response(request,
                                        bundle,
                                        response_class=http.HttpBadRequest)
Exemplo n.º 6
0
    def _build_filters(self, filters=None, ignore_bad_filters=False):
        """
        Overrides BaseModelResource.build_filters to support query terms for related fields
        https://github.com/django-tastypie/django-tastypie/issues/1618
        """

        if filters is None:
            filters = {}

        qs_filters = {}

        for filter_expr, value in filters.items():
            filter_bits = filter_expr.split(LOOKUP_SEP)
            field_name = filter_bits.pop(0)

            if field_name not in self.fields:
                # It's not a field we know about. Move along citizen.
                continue

            try:
                filter_type = self.resolve_filter_type(field_name, filter_bits, "exact")
                lookup_bits = self.check_filtering(field_name, filter_type, filter_bits)
            except InvalidFilterError:
                if ignore_bad_filters:
                    continue
                else:
                    raise
            value = self.filter_value_to_python(value, field_name, filters, filter_expr, filter_type)

            qs_filter = LOOKUP_SEP.join(lookup_bits)
            qs_filters[qs_filter] = value

        return dict_strip_unicode_keys(qs_filters)
Exemplo n.º 7
0
    def update_temp_batches(self, request, **kwargs):
        '''Update a set of molecules into elasticsearch (used in ChemBio Hub to set the action field to ignore or new batch)'''
        deserialized = self.deserialize(request, request.body, format=request.META.get(
            'CONTENT_TYPE', 'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(
                self.get_object_list(bundle.request), bundle)
        else:
            self.authorized_create_detail(
                self.get_object_list(bundle.request), bundle)
        multi_batch_id = bundle.data["multiplebatch"]
        es_ready_updates = bundle.data["objects"]

        index_name = elasticsearch_client.get_temp_index_name(
            request.COOKIES[settings.SESSION_COOKIE_NAME], multi_batch_id)

        elasticsearch_client.create_temporary_index(
            es_ready_updates, index_name)
        elasticsearch_client.get_action_totals(index_name, bundle.data)
        return self.create_response(request, bundle, response_class=http.HttpAccepted)
Exemplo n.º 8
0
    def put_list(self, request, **kwargs):
        """
        based on tastypie/resources.py but modified to do what we actually want!

        Up a collection of resources with another collection.

        Calls ``delete_list`` to clear out the collection then ``obj_create``
        with the provided the data to create the new collection.

        Return ``HttpNoContent`` (204 No Content) if
        ``Meta.always_return_data = False`` (default).

        Return ``HttpAccepted`` (202 Accepted) if
        ``Meta.always_return_data = True``.
        """
        deserialized = self.deserialize(request,
                                        request.raw_post_data,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_list_data(request, deserialized)

        if not 'objects' in deserialized:
            raise http.HttpBadRequest("Invalid data sent.")

        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)

        self.obj_update(bundle, **kwargs)
Exemplo n.º 9
0
    def put_list(self, request, **kwargs):
        """
        Replaces a collection of resources with another collection.

        Unlike the default put_list, this doesn't expect the new collections
        to be wrapped in an 'objects' property.
        """
        deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_list_data(request, deserialized)

        basic_bundle = self.build_bundle(request=request)
        self.obj_delete_list_for_update(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
        bundles_seen = []

        for object_data in deserialized:
            bundle = self.build_bundle(data=dict_strip_unicode_keys(object_data), request=request)

            # Attempt to be transactional, deleting any previously created
            # objects if validation fails.
            try:
                self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))
                bundles_seen.append(bundle)
            except ImmediateHttpResponse:
                self.rollback(bundles_seen)
                raise

        if not self._meta.always_return_data:
            return http.HttpNoContent()
        else:
            to_be_serialized = {}
            to_be_serialized[self._meta.collection_name] = [self.full_dehydrate(bundle) for bundle in bundles_seen]
            to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)
            return self.create_response(request, to_be_serialized, response_class=http.HttpAccepted)
Exemplo n.º 10
0
    def put_detail(self, request, **kwargs):
        """
        Copied from tastypie ModelResource so we dont try to create one
        if it doesn't exist.
        """
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)

        try:
            updated_bundle = self.obj_update(
                bundle=bundle, **self.remove_api_resource_names(kwargs))

            if not self._meta.always_return_data:
                return http.HttpNoContent()
            else:
                # Invalidate prefetched_objects_cache for bundled object
                # because we might have changed a prefetched field
                updated_bundle.obj._prefetched_objects_cache = {}
                updated_bundle = self.full_dehydrate(updated_bundle)
                updated_bundle = self.alter_detail_data_to_serialize(
                    request, updated_bundle)
                return self.create_response(request, updated_bundle)
        except (NotFound, MultipleObjectsReturned):
            return self.create_response(request,
                                        'Object not found',
                                        response_class=HttpNotFound)
Exemplo n.º 11
0
    def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        fk_bundle = fk_resource.build_bundle(data=data, request=request)

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        # We need to check to see if updates are allowed on the FK
        # resource. If not, we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        if not fk_resource.can_update():
            return fk_resource.full_hydrate(fk_bundle)

        try:
            return fk_resource.obj_update(fk_bundle, skip_errors=True, **data)
        except NotFound:
            try:
                # Attempt lookup by primary key
                lookup_kwargs = dict((k, v) for k, v in data.iteritems() if getattr(fk_resource, k).unique)

                if not lookup_kwargs:
                    raise NotFound()
                return fk_resource.obj_update(fk_bundle, skip_errors=True, **lookup_kwargs)
            except NotFound:
                fk_bundle = fk_resource.full_hydrate(fk_bundle)
                fk_resource.is_valid(fk_bundle, request)
                return fk_bundle
        except MultipleObjectsReturned:
            return fk_resource.full_hydrate(fk_bundle)
Exemplo n.º 12
0
    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        qs_filters = {}

        if getattr(self._meta, 'queryset', None) is not None:
            # Get the possible query terms from the current QuerySet.
            query_terms = self._meta.queryset.query.query_terms
        else:
            query_terms = QUERY_TERMS

        for filter_expr, value in filters.items():
            filter_bits = filter_expr.split(LOOKUP_SEP)
            field_name = filter_bits.pop(0)
            filter_type = 'exact'

            if not field_name in self.fields:
                # It's not a field we know about. Move along citizen.
                continue

            if len(filter_bits) and filter_bits[-1] in query_terms:
                filter_type = filter_bits.pop()

            lookup_bits = self.check_filtering(field_name, filter_type, filter_bits)
            value = self.filter_value_to_python(value, field_name, filters, filter_expr, filter_type)

            db_field_name = LOOKUP_SEP.join(lookup_bits)
            qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
            qs_filters[qs_filter] = value

        return dict_strip_unicode_keys(qs_filters)
Exemplo n.º 13
0
    def multi_batch_custom_fields(self, request, **kwargs):
        '''change the structure column for an excel file'''
        deserialized = self.deserialize(request, request.body, format=request.META.get(
            'CONTENT_TYPE', 'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(
                self.get_object_list(bundle.request), bundle)
        else:
            self.authorized_create_detail(
                self.get_object_list(bundle.request), bundle)
        id = bundle.data["multiplebatch"]
        headers = bundle.data["headers"]
        # structure_col = bundle.data.get("structure_col", None)
        mb = CBHCompoundMultipleBatch.objects.get(pk=id)
        processSmiles = False
        # if structure_col and structure_col != mb.uploaded_data.get("structure_col", ""):
        #     processSmiles =  True
        index_name = elasticsearch_client.get_temp_index_name(request.COOKIES[settings.SESSION_COOKIE_NAME], mb.id)
        elasticsearch_client.get_action_totals(index_name, bundle.data)
        mb.uploaded_data = bundle.data
        mb.save()
        return self.create_response(request, bundle, response_class=http.HttpAccepted)
Exemplo n.º 14
0
    def patch_list(self, request=None, **kwargs):
        """
        Exactly copied from https://github.com/toastdriven/django-tastypie/blob/v0.9.14/tastypie/resources.py#L1466
        (BSD licensed) and modified to pass the kwargs to `obj_create` and support only create method
        """
        request = convert_post_to_patch(request)
        deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))

        collection_name = self._meta.collection_name
        if collection_name not in deserialized:
            raise BadRequest("Invalid data sent: missing '%s'" % collection_name)

        if len(deserialized[collection_name]) and 'put' not in self._meta.detail_allowed_methods:
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())

        bundles_seen = []
        status = http.HttpAccepted
        for data in deserialized[collection_name]:

            data = self.alter_deserialized_detail_data(request, data)
            bundle = self.build_bundle(data=dict_strip_unicode_keys(data), request=request)
            try:

                self.obj_create(bundle=bundle, **self.remove_api_resource_names(kwargs))
            except AssertionError as ex:
                status = http.HttpBadRequest
                bundle.data['_id'] = ex.message
            bundles_seen.append(bundle)

        to_be_serialized = [bundle.data['_id'] for bundle in bundles_seen]
        return self.create_response(request, to_be_serialized, response_class=status)
Exemplo n.º 15
0
    def post_list(self, request, **kwargs):
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        content_object = self.content_object.hydrate(bundle).obj
        obj = Accuracy.objects.filter(
            user=bundle.request.user,
            content_type=ContentType.objects.get_for_model(content_object),
            object_id=content_object.id)
        if obj.exists():
            bundle = self.full_bundle(obj[0], bundle.request)
            super(AccuracyResource, self).obj_delete(bundle, **kwargs)
            return http.HttpNoContent()
        updated_bundle = self.obj_create(
            bundle, **self.remove_api_resource_names(kwargs))
        location = self.get_resource_uri(updated_bundle)

        if not self._meta.always_return_data:
            return http.HttpCreated(location=location)
        else:
            updated_bundle = self.full_dehydrate(updated_bundle)
            updated_bundle = self.alter_detail_data_to_serialize(
                request, updated_bundle)
            return self.create_response(request,
                                        updated_bundle,
                                        response_class=http.HttpCreated,
                                        location=location)
Exemplo n.º 16
0
    def update_temp_batches(self, request, **kwargs):
        '''Update a set of molecules into elasticsearch (used in ChemBio Hub to set the action field to ignore or new batch)'''
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request),
                                          bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request),
                                          bundle)
        multi_batch_id = bundle.data["multiplebatch"]
        es_ready_updates = bundle.data["objects"]

        index_name = elasticsearch_client.get_temp_index_name(
            request.COOKIES[settings.SESSION_COOKIE_NAME], multi_batch_id)

        elasticsearch_client.create_temporary_index(es_ready_updates,
                                                    index_name)
        elasticsearch_client.get_action_totals(index_name, bundle.data)
        return self.create_response(request,
                                    bundle,
                                    response_class=http.HttpAccepted)
Exemplo n.º 17
0
    def patch_list(self, request=None, **kwargs):
        """
        Exactly copied from https://github.com/toastdriven/django-tastypie/blob/v0.9.14/tastypie/resources.py#L1466
        (BSD licensed) and modified to pass the kwargs to `obj_create` and support only create method
        """
        request = convert_post_to_patch(request)
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

        collection_name = self._meta.collection_name
        if collection_name not in deserialized:
            raise BadRequest("Invalid data sent: missing '%s'" % collection_name)

        if len(deserialized[collection_name]) and 'put' not in self._meta.detail_allowed_methods:
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())

        bundles_seen = []
        status = http.HttpAccepted
        for data in deserialized[collection_name]:

            data = self.alter_deserialized_detail_data(request, data)
            bundle = self.build_bundle(data=dict_strip_unicode_keys(data), request=request)
            try:

                self.obj_create(bundle=bundle, **self.remove_api_resource_names(kwargs))
            except AssertionError as ex:
                status = http.HttpBadRequest
                bundle.data['_id'] = ex.message
            bundles_seen.append(bundle)

        to_be_serialized = [bundle.data['_id'] for bundle in bundles_seen]
        return self.create_response(request, to_be_serialized, response_class=status)
Exemplo n.º 18
0
    def delete_index(self, request, **kwargs):
        """Delete the index that was created for a multiple batch"""
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request),
                                          bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request),
                                          bundle)
        id = bundle.data["multiplebatch"]
        mb = CBHCompoundMultipleBatch.objects.get(pk=id)
        elasticsearch_client.delete_index(
            elasticsearch_client.get_temp_index_name(session_key, mb.id))
        return self.create_response(request,
                                    bundle,
                                    response_class=http.HttpAccepted)
Exemplo n.º 19
0
    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        qs_filters = {}

        if getattr(self._meta, 'queryset', None) is not None:
            # Get the possible query terms from the current QuerySet.
            query_terms = self._meta.queryset.query.query_terms
        else:
            query_terms = QUERY_TERMS

        for filter_expr, value in filters.items():
            filter_bits = filter_expr.split(LOOKUP_SEP)
            field_name = filter_bits.pop(0)
            filter_type = 'exact'

            if not field_name in self.fields:
                # It's not a field we know about. Move along citizen.
                continue

            if len(filter_bits) and filter_bits[-1] in query_terms:
                filter_type = filter_bits.pop()

            lookup_bits = self.check_filtering(field_name, filter_type,
                                               filter_bits)
            value = self.filter_value_to_python(value, field_name, filters,
                                                filter_expr, filter_type)

            db_field_name = LOOKUP_SEP.join(lookup_bits)
            qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
            qs_filters[qs_filter] = value

        return dict_strip_unicode_keys(qs_filters)
Exemplo n.º 20
0
 def build_related_resource(self, value):
     """
     Used to ``hydrate`` the data provided. If just a URL is provided,
     the related resource is attempted to be loaded. If a
     dictionary-like structure is provided, a fresh resource is
     created.
     """
     self.fk_resource = self.to_class()
     
     if isinstance(value, basestring):
         # We got a URI. Load the object and assign it.
         try:
             obj = self.fk_resource.get_via_uri(value)
             return self.fk_resource.full_dehydrate(obj)
         except ObjectDoesNotExist:
             raise ApiFieldError("Could not find the provided object via resource URI '%s'." % value)
     elif hasattr(value, 'items'):
         # Try to hydrate the data provided.
         value = dict_strip_unicode_keys(value)
         self.fk_bundle = Bundle(data=value)
         try:
             return self.fk_resource.obj_update(self.fk_bundle, **value)
         except NotFound:
             try:
                 # Attempt lookup by primary key
                 lookup_kwargs = dict((k, v) for k, v in value.iteritems() if getattr(self.fk_resource, k).unique)
                 if not lookup_kwargs:
                     raise NotFound
                 return self.fk_resource.obj_update(self.fk_bundle, **lookup_kwargs)
             except NotFound:
                 return self.fk_resource.full_hydrate(self.fk_bundle)
         except MultipleObjectsReturned:
             return self.fk_resource.full_hydrate(self.fk_bundle)
     else:
         raise ApiFieldError("The '%s' field has was given data that was not a URI and not a dictionary-alike: %s." % (self.instance_name, value))
Exemplo n.º 21
0
    def put_detail(self, request, **kwargs):
        """Override put_detail so that it doesn't create a new resource when
        One doesn't exists, I don't like this reflex"""
        if VERSION >= (1, 4):
            body = request.body
        else:
            body = request.raw_post_data
        deserialized = self.deserialize(request,
                                        body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)

        try:
            updated_bundle = self.obj_update(
                bundle=bundle, **self.remove_api_resource_names(kwargs))

            if not self._meta.always_return_data:
                return http.HttpNoContent()
            else:
                updated_bundle = self.full_dehydrate(updated_bundle)
                updated_bundle = self.alter_detail_data_to_serialize(
                    request, updated_bundle)
                return self.create_response(request,
                                            updated_bundle,
                                            response_class=http.HttpAccepted)
        except (NotFound, MultipleObjectsReturned):
            raise NotFound(
                "A model instance matching the provided arguments could not be found."
            )
Exemplo n.º 22
0
    def multi_batch_custom_fields(self, request, **kwargs):
        '''change the structure column for an excel file'''
        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request),
                                          bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request),
                                          bundle)
        id = bundle.data["multiplebatch"]
        headers = bundle.data["headers"]
        # structure_col = bundle.data.get("structure_col", None)
        mb = CBHCompoundMultipleBatch.objects.get(pk=id)
        processSmiles = False
        # if structure_col and structure_col != mb.uploaded_data.get("structure_col", ""):
        #     processSmiles =  True
        index_name = elasticsearch_client.get_temp_index_name(
            request.COOKIES[settings.SESSION_COOKIE_NAME], mb.id)
        elasticsearch_client.get_action_totals(index_name, bundle.data)
        mb.uploaded_data = bundle.data
        mb.save()
        return self.create_response(request,
                                    bundle,
                                    response_class=http.HttpAccepted)
Exemplo n.º 23
0
    def put_detail(self, request, **kwargs):
        """
        Either updates an existing resource or creates a new one with the
        provided data.
        
        Calls ``obj_update`` with the provided data first, but falls back to
        ``obj_create`` if the object does not already exist.
        
        If a new resource is created, return ``HttpCreated`` (201 Created).
        If an existing resource is modified, return ``HttpAccepted`` (204 No Content).
        """
        deserialized = self.deserialize(request,
                                        request.raw_post_data,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
        self.is_valid(bundle, request)

        try:
            updated_bundle = self.obj_update(bundle, request=request, **kwargs)
            return HttpAccepted()
        except:
            updated_bundle = self.obj_create(bundle, request=request, **kwargs)
            return HttpCreated(location=self.get_resource_uri(updated_bundle))
Exemplo n.º 24
0
 def build_related_resource(self, value):
     """
     Used to ``hydrate`` the data provided. If just a URL is provided,
     the related resource is attempted to be loaded. If a
     dictionary-like structure is provided, a fresh resource is
     created.
     """
     self.fk_resource = self.to_class()
     
     if isinstance(value, basestring):
         # We got a URI. Load the object and assign it.
         try:
             obj = self.fk_resource.get_via_uri(value)
             return self.fk_resource.full_dehydrate(obj)
         except ObjectDoesNotExist:
             raise ApiFieldError("Could not find the provided object via resource URI '%s'." % value)
     elif hasattr(value, 'items'):
         # Try to hydrate the data provided.
         value = dict_strip_unicode_keys(value)
         self.fk_bundle = Bundle(data=value)
         try:
             return self.fk_resource.obj_update(self.fk_bundle, **value)
         except NotFound:
             try:
                 # Attempt lookup by primary key
                 lookup_kwargs = dict((k, v) for k, v in value.iteritems() if getattr(self.fk_resource, k).unique)
                 if not lookup_kwargs:
                     raise NotFound
                 return self.fk_resource.obj_update(self.fk_bundle, **lookup_kwargs)
             except NotFound:
                 return self.fk_resource.full_hydrate(self.fk_bundle)
         except MultipleObjectsReturned:
             return self.fk_resource.full_hydrate(self.fk_bundle)
     else:
         raise ApiFieldError("The '%s' field has was given data that was not a URI and not a dictionary-alike: %s." % (self.instance_name, value))
Exemplo n.º 25
0
    def post_list(self, request, **kwargs):
        """
        Creates a new resource/object with the provided data.

        Calls ``obj_create`` with the provided data and returns a response
        with the new resource's location.

        If a new resource is created, return ``HttpCreated`` (201 Created).
        If ``Meta.always_return_data = True``, there will be a populated body
        of serialized data.
        """
        bundle = self.build_bundle(data=dict_strip_unicode_keys(request.POST), request=request)
        bundle.files = request.FILES

        updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
        location = self.get_resource_uri(updated_bundle)

        if not self._meta.always_return_data:
            return http.HttpCreated(location=location)
        else:
            updated_bundle = self.full_dehydrate(updated_bundle)
            updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
            return self.create_upload_response(
                request, updated_bundle, response_class=http.HttpCreated, location=location
            )
Exemplo n.º 26
0
Arquivo: api.py Projeto: alecw/TS
    def put_plugin(self, request, **kwargs):
        """
        Set the status of the plugins.
        This allow a way to see if the plugin was ran successfully.
        """

        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        data=dict_strip_unicode_keys(deserialized)
        results = self.get_object_list(request).get(pk=kwargs["pk"])
        if results is None:
            return HttpGone()
        #we are only doing to use the first value of the dict
        if len(data) != 1:
            return HttpBadRequest()

        try:
            with transaction.commit_on_success():
                for (key, value) in data.items():
                    # Note: If multiple plugins exist, use one with last install date.
                    # FIXME Must uniquely identify plugins
                    plugin = models.Plugin.objects.get(name=key,active=True)
                    (pluginresult, created) = results.pluginresult_set.get_or_create(plugin=plugin)
                    pluginresult.state = value
                    pluginresult.save()
        except:
            logger.exception('Failed plugin state update')
            return HttpBadRequest()

        return HttpAccepted()
Exemplo n.º 27
0
    def patch_detail(self, request, **kwargs):
        """
        Processa requisição PATCH, para modificação do usuário em questão.
        """

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------

        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        self._meta.validation = CleanedDataFormValidation(
            form_class=UserUpdateForm)
        self.is_valid(bundle)
        
        if bundle.errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, bundle.errors['user']))

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------

        user_update(username=kwargs['username'], data=bundle.data)


        return self.create_response(request, bundle, 
            response_class=http.HttpAccepted)

        return http.HttpAccepted()
Exemplo n.º 28
0
    def social_share(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)

        try:
            social_obj = self._meta.queryset._clone().get(pk=kwargs['pk'])
        except self._meta.object_class.DoesNotExist:
            return http.HttpNotFound()

        deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        bundle = self.build_bundle(obj=social_obj, request=request, data=dict_strip_unicode_keys(deserialized))

        try:
            auth_result = self._meta.authorization.share_detail(None, bundle)
            if not auth_result is True:
                raise Unauthorized()
        except Unauthorized as e:
            self.unauthorized_result(e)
        except AttributeError as e:
            raise NotImplementedError("You must create a share_detail authorization method")

        if 'provider' not in bundle.data:
            return self.error_response(request, {"error": "No provider parameter given"}, response_class=http.HttpBadRequest)

        try:
            user_social_auth = UserSocialAuth.objects.get(user=bundle.request.user, provider=bundle.data['provider'])

            # Inline import to remove recursive importing
            from manticore_tastypie_social.manticore_tastypie_social.utils import post_social_media
            post_social_media.delay(user_social_auth, bundle.obj.pk)
        except UserSocialAuth.DoesNotExist:
            return self.error_response(request, {"error": "User is not authenticated with %s" % bundle.data['provider']}, response_class=http.HttpBadRequest)
        except BadRequest, e:
            return self.error_response(request, {"error": e}, response_class=http.HttpBadRequest)
Exemplo n.º 29
0
 def post_list(self, request, **kwargs):
     deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
     deserialized = self.alter_deserialized_list_data(request, deserialized)
     bundle = self.build_bundle_custom_class(data=dict_strip_unicode_keys(deserialized), request=request)
     self.is_valid(bundle, request)
     updated_bundle = self.obj_create(bundle, request=request)
     return HttpCreated(location=self.get_resource_uri(updated_bundle))
Exemplo n.º 30
0
 def post_list(self, request, **kwargs):
     deserialized = self.deserialize(request, request.body,
                                     format=request.META.get('CONTENT_TYPE', 'application/json'))
     deserialized = self.alter_deserialized_detail_data(request, deserialized)
     data = dict_strip_unicode_keys(deserialized)
     if 'objects' not in data:
         raise BadRequest('Missing objects list.')
     if not data.get('objects'):
         raise BadRequest('Empty objects list.')
     base_bundle = self.build_bundle(request=request)
     supposed_objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs))
     received_numbers = [obj['material_number'] for obj in data.get('objects')]
     received_filters = {'material_number__in': received_numbers}
     received_objects = self.get_object_list(request).filter(**received_filters)
     tp_objects = [obj for obj in received_objects if obj in supposed_objects]
     fn_objects = [obj for obj in received_objects if obj not in supposed_objects]
     fp_objects = [obj for obj in supposed_objects if obj not in received_objects]
     all_objects = {
         'tp': tp_objects,
         'fn': fn_objects,
         'fp': fp_objects
     }
     for status, objects in all_objects.iteritems():
         for obj in objects:
             Log.create(
                 user=request.user,
                 luggage=obj,
                 status=status
             )
     return http.HttpCreated()
Exemplo n.º 31
0
    def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        fk_bundle = fk_resource.build_bundle(data=data, request=request)

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        # We need to check to see if updates are allowed on the FK
        # resource. If not, we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        if not fk_resource.can_update():
            return fk_resource.full_hydrate(fk_bundle)

        try:
            return fk_resource.obj_update(fk_bundle, skip_errors=True, **data)
        except NotFound:
            try:
                # Attempt lookup by primary key
                lookup_kwargs = dict((k, v) for k, v in data.iteritems() if getattr(fk_resource, k).unique)

                if not lookup_kwargs:
                    raise NotFound()
                return fk_resource.obj_update(fk_bundle, skip_errors=True, **lookup_kwargs)
            except NotFound:
                fk_bundle = fk_resource.full_hydrate(fk_bundle)
                fk_resource.is_valid(fk_bundle, request)
                return fk_bundle
        except MultipleObjectsReturned:
            return fk_resource.full_hydrate(fk_bundle)
Exemplo n.º 32
0
    def _staff_or_instructor_delete_list(self, request, **kwargs):

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------

        course_id = course_id_decoder(kwargs['pk'])
        staff_or_instructor = kwargs['staff_or_instructor']
        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = Bundle(data=dict_strip_unicode_keys(deserialized), 
            request=request)
        
        if 'user_resource_uri' in bundle.data:  
            user_resource_uri = bundle.data['user_resource_uri']
        bundle.data['course_id'] = course_id
        bundle.data['staff_or_instructor'] = kwargs['staff_or_instructor']

        validation = CleanedDataFormValidation(form_class=CourseDeleteUserForm)
        validation_errors = validation.is_valid(bundle)
        
        if validation_errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, validation_errors))

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------

        username = user_resource_uri.split('/')[-2:-1][0]
        course_remove_user(course_id, username, staff_or_instructor)
        return http.HttpNoContent()
Exemplo n.º 33
0
    def post_list(self, request, **kwargs):        

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------

        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = Bundle(data=dict_strip_unicode_keys(deserialized), 
            request=request)
        validation = CleanedDataFormValidation(form_class=CourseCreateForm)
        validation_errors = validation.is_valid(bundle)

        if validation_errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, validation_errors))        

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------

        course_create(bundle.data)

        # Adicionando ``resource_uri``
        bundle.data['resource_uri'] = reverse('api_dispatch_detail', 
            kwargs={ 'api_name': CourseResource._meta.api_name,
            'resource_name': CourseResource._meta.resource_name, 
            'course_id_solaredx': course_id_encoder(bundle.data['course_id'])})

        return self.create_response(request, bundle, 
            response_class=http.HttpCreated)
Exemplo n.º 34
0
    def _enrollment_delete_list(self, request, **kwargs):
        " Desmatricula aluno em curso. "

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------

        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        bundle.data['username'] = kwargs['pk']
        self._meta.validation = CleanedDataFormValidation(
            form_class=UserUnenrollForm)
        self.is_valid(bundle)
        
        if bundle.errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, bundle.errors['user']))

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------
        
        course_id = course_id_decoder(
            bundle.data['course_resource_uri'].split('/')[5])
        user_unenroll(kwargs['pk'], course_id)
        return http.HttpNoContent()
Exemplo n.º 35
0
    def delete_detail(self, request, **kwargs):
        """
        Processa requisição DELETE, para exclusão do usuário em questão.
        """

        # Chamada não permitida
        return http.HttpMethodNotAllowed()

        # ETAPA 1 - Desserialização e validação dos dados recebidos
        # ---------------------------------------------------------        

        deserialized = self.deserialize(request, request.body, 
            format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        self._meta.validation = CleanedDataFormValidation(
            form_class=UserDeleteForm)
        self.is_valid(bundle)
        
        if bundle.errors:
            raise ImmediateHttpResponse(response=self.error_response(
                bundle.request, bundle.errors))

        # ETAPA 2 - Efetuando operações no EDX
        # ------------------------------------

        user_delete(username=kwargs['username'])
        return http.HttpNoContent()
Exemplo n.º 36
0
    def post_list(self, request, **kwargs):
        """
        Creates a new resource/object with the provided data.

        Calls ``obj_create`` with the provided data and returns a response
        with the new resource's location.

        If a new resource is created, return ``HttpCreated`` (201 Created).
        """
        deserialized = self.deserialize(request,
                                        request.raw_post_data,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
        self.is_valid(bundle, request)

        updated_bundle = self.obj_create(bundle,
                                         request=request,
                                         user=request.user)

        updated_bundle.obj.get_tracks()
        #        updated_bundle.obj.get_track_urls()

        # return self.create_response(request, {'id': updated_bundle.obj.id, "track_list": track_list })
        return self.create_response(request, self.full_dehydrate(bundle.obj))
Exemplo n.º 37
0
    def update_in_place(self, request, original_bundle, new_data):
        """
        Update the object in original_bundle in-place using new_data.
        """
        updated = dict_strip_unicode_keys(new_data)

        usable = {}
        permitted_values = ['label', 'level', 'qualifiers']

        for pv in permitted_values:
            if pv in updated:
                usable[pv] = updated[pv]

        user = get_real_user_object(request.user)

        # maybe should be pk, or uri not user object...
        usable['labeller'] = user

        original_bundle.data.update(**usable)

        # Now we've got a bundle with the new data sitting in it and we're
        # we're basically in the same spot as a PUT request. SO the rest of this
        # function is cribbed from put_detail.
        self.alter_deserialized_detail_data(request, original_bundle.data)
        kwargs = {
            self._meta.detail_uri_name: self.get_bundle_detail_data(original_bundle),
            'request': request,
        }
        return self.obj_update(bundle=original_bundle, **kwargs)
Exemplo n.º 38
0
    def put_detail(self, request, **kwargs):
        """
        Either updates an existing resource or creates a new one with the
        provided data.

        Calls ``obj_update`` with the provided data first, but falls back to
        ``obj_create`` if the object does not already exist.

        If a new resource is created, return ``HttpCreated`` (201 Created).
        If ``Meta.always_return_data = True``, there will be a populated body
        of serialized data.

        If an existing resource is modified and
        ``Meta.always_return_data = False`` (default), return ``HttpNoContent``
        (204 No Content).
        If an existing resource is modified and
        ``Meta.always_return_data = True``, return ``HttpAccepted`` (202
        Accepted).
        """
        fmt = request.META.get('CONTENT_TYPE', 'application/json')
        if fmt.startswith('multipart'):
            body = None
        else:
            body = request.body
        deserialized = self.deserialize(request, body, format=fmt)
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)

        try:
            updated_bundle = self.obj_update(
                bundle=bundle, **self.remove_api_resource_names(kwargs))

            if not self._meta.always_return_data:
                return http.HttpNoContent()
            else:
                updated_bundle = self.full_dehydrate(updated_bundle)
                updated_bundle = self.alter_detail_data_to_serialize(
                    request, updated_bundle)
                return self.create_response(request,
                                            updated_bundle,
                                            response_class=http.HttpAccepted)
        except (NotFound, MultipleObjectsReturned):
            updated_bundle = self.obj_create(
                bundle=bundle, **self.remove_api_resource_names(kwargs))
            location = self.get_resource_uri(updated_bundle)

            if not self._meta.always_return_data:
                return http.HttpCreated(location=location)
            else:
                updated_bundle = self.full_dehydrate(updated_bundle)
                updated_bundle = self.alter_detail_data_to_serialize(
                    request, updated_bundle)
                return self.create_response(request,
                                            updated_bundle,
                                            response_class=http.HttpCreated,
                                            location=location)
Exemplo n.º 39
0
    def post_validate_list(self, request, **kwargs):
        """
        When a list of SMILES patterns are submitted, save them to elasticsearhc and
        call the normal validate multi batch function to give the normal statistics page
        """
        session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
        deserialized = self.deserialize(request, request.body, format=request.META.get(
            'CONTENT_TYPE', 'application/json'))

        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)
        bundle = self.build_bundle(
            data=dict_strip_unicode_keys(deserialized), request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(
                self.get_object_list(bundle.request), bundle)
        else:
            self.authorized_create_detail(
                self.get_object_list(bundle.request), bundle)
        smilesdata = bundle.data.get("smilesdata", "")
        objects = [smi.strip() for smi in smilesdata.splitlines(True)]
        batches = []
        # first assume smiles
        allmols = [(obj, Chem.MolFromSmiles(str(obj))) for obj in objects]
        # Next test for inchi
        multiple_batch = CBHCompoundMultipleBatch.objects.create(
            project=bundle.data["project"], batch_count=len(allmols))
        for index, m in enumerate(allmols):
            if m[1] is None:
                inchimol = Chem.MolFromInchi(
                    str(m[0].encode('ascii', 'ignore')))
                if inchimol is not None:
                    allmols[index] = (Chem.MolToSmiles(inchimol), inchimol)
        for m in allmols:
            if(m[1]):
                Compute2DCoords(m[1])
        batches = []
        
        for mol2 in allmols:
            if mol2[1]:
                b = CBHCompoundBatch.objects.from_rd_mol(
                    mol2[1], smiles=mol2[0], project=bundle.data["project"], reDraw=True)
            else:
                b = CBHCompoundBatch.objects.blinded(
                    project=bundle.data["project"])
                b.warnings["smilesParseError"] = "true"
                b.properties["action"] = "Ignore"
                b.original_smiles = mol2[0]
            b.multiple_batch_id = multiple_batch.pk
            b.created_by = bundle.request.user.username
            b.created_by_id = bundle.request.user.id
            batches.append(b)

        bundle.data["current_batch"] = multiple_batch.pk
        bundle.data["headers"] = []
        validate_multi_batch(self, multiple_batch, bundle.data, session_key, batches)
        return self.create_response(request, bundle, response_class=http.HttpAccepted)
Exemplo n.º 40
0
    def build_filters(self, filters=None):
        """
        Given a dictionary of filters, create the necessary ORM-level filters.

        Keys should be resource fields, **NOT** model fields.

        Valid values are either a list of Django filter types (i.e.
        ``['startswith', 'exact', 'lte']``), the ``ALL`` constant or the
        ``ALL_WITH_RELATIONS`` constant.
        """
        # At the declarative level:
        #     filtering = {
        #         'resource_field_name': ['exact', 'startswith', 'endswith', 'contains'],
        #         'resource_field_name_2': ['exact', 'gt', 'gte', 'lt', 'lte', 'range'],
        #         'resource_field_name_3': ALL,
        #         'resource_field_name_4': ALL_WITH_RELATIONS,
        #         ...
        #     }
        # Accepts the filters as a dict. None by default, meaning no filters.
        if filters is None:
            filters = {}

        qs_filters = {}

        for filter_expr, value in filters.items():
            filter_bits = filter_expr.split(LOOKUP_SEP)
            field_name = filter_bits.pop(0)
            filter_type = 'exact'

            if not field_name in self.fields:
                # It's not a field we know about. Move along citizen.
                continue

            if len(filter_bits) and filter_bits[-1] in QUERY_TERMS.keys():
                filter_type = filter_bits.pop()

            lookup_bits = self.check_filtering(field_name, filter_type, filter_bits)

            if value in ['true', 'True', True]:
                value = True
            elif value in ['false', 'False', False]:
                value = False
            elif value in ('nil', 'none', 'None', None):
                value = None

            # Split on ',' if not empty string and either an in or range filter.
            if filter_type in ('in', 'range') and len(value):
                if hasattr(filters, 'getlist'):
                    value = filters.getlist(filter_expr)
                else:
                    value = value.split(',')

            db_field_name = LOOKUP_SEP.join(lookup_bits)
            qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
            qs_filters[qs_filter] = value

        return dict_strip_unicode_keys(qs_filters)
Exemplo n.º 41
0
    def post_list(self, request, **kwargs):
        from tastypie import http
        from tastypie.utils import dict_strip_unicode_keys
        """
        Creates a new resource/object with the provided data.

        Calls ``obj_create`` with the provided data and returns a response
        with the new resource's location.

        If a new resource is created, return ``HttpCreated`` (201 Created).
        If ``Meta.always_return_data = True``, there will be a populated body
        of serialized data.
        """
        
        '''
        This method is overridden only for the purpose of accepting a 'multipart'
        request for the purpose of receiving a 'submission' file.
        Changes of the original method are enclosed in <--- CHANGE ---> tags. (commented)
        '''
        
        '''<--- CHANGE ---> '''
        '''
        For some reason without accessing the variable request it fails,
        so without the debugging line print it won't work
        '''
        import logging
        logging.debug(request.FILES)
        if request.META.get('CONTENT_TYPE').startswith('multipart'):
            request.META['CONTENT_TYPE'] = 'application/json'
            #===================================================================
            # if ' name' in request.POST:
            #    data = self.strip_multiForm(request.POST[' name'])
            #    logging.debug('SDADSA')
            #    #logging.debug(data[1098] + data[1099] + data[1100] + data[1101])
            # else:
            #    data = request.POST['data']
            #===================================================================
            if not 'data' in request.POST:
                return ImmediateHttpResponse(HttpBadRequest)
            deserialized = self.deserialize(request, request.POST['data'], format=request.META.get('CONTENT_TYPE', 'application/json'))
            
        else:
            deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        ''' <--- CHANGE ---> '''
        
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))
        location = self.get_resource_uri(updated_bundle)

        if not self._meta.always_return_data:
            return http.HttpCreated(location=location)
        else:
            updated_bundle = self.full_dehydrate(updated_bundle)
            updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
            return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
Exemplo n.º 42
0
    def resource_from_data(self,
                           fk_resource,
                           data,
                           request=None,
                           related_obj=None,
                           related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        fk_bundle = fk_resource.build_bundle(data=data, request=request)

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        # We need to check to see if updates are allowed on the FK
        # resource. If not, we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        if not fk_resource.can_update():

            # If the resource already exists and the client specified where to find it, we look it up.
            if 'resource_uri' in data:
                obj = fk_resource.get_via_uri(data['resource_uri'],
                                              request=request)
                fk_bundle.install_existing_obj(obj)
                return fk_bundle

            # If the resource supports creation, then we can full_hydrate() and create a new instance.
            elif fk_resource.can_create():
                return fk_resource.full_hydrate(fk_bundle)

            else:
                raise ApiFieldError(
                    "Resource %s does not support being created via POST" %
                    fk_resource._meta.resource_name)

        try:
            return fk_resource.obj_update(fk_bundle, **data)
        except NotFound:
            try:
                # Attempt lookup by primary key
                lookup_kwargs = dict((k, v) for k, v in data.iteritems()
                                     if getattr(fk_resource, k).unique)

                if not lookup_kwargs:
                    raise NotFound()
                return fk_resource.obj_update(fk_bundle, **lookup_kwargs)
            except NotFound:
                fk_bundle = fk_resource.full_hydrate(fk_bundle)
                fk_resource.is_valid(fk_bundle, request)
                return fk_bundle
        except MultipleObjectsReturned:
            return fk_resource.full_hydrate(fk_bundle)
Exemplo n.º 43
0
 def put_detail(self, request, **kwargs):
     deserialized = self.deserialize(request,
                                     request.raw_post_data,
                                     format=request.META.get(
                                         'CONTENT_TYPE',
                                         'application/json'))
     bundle = dict_strip_unicode_keys(deserialized)
     updated_bundle = self.obj_update(
         bundle, request=request, **self.remove_api_resource_names(kwargs))
     return self.create_response(request, updated_bundle)
Exemplo n.º 44
0
    def create_reading_list(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        deserialized = self.deserialize(request, request.body,
                                        format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        ReadingList(user=request.user, private=bundle.data.get("private")).save()

        return self.create_response(request, {})
Exemplo n.º 45
0
Arquivo: data.py Projeto: Rawadx/panda
    def put_list(self, request, **kwargs):
        """
        A custom bulk create/update handler. Notes: 

        * ``obj_delete_list`` is never called, objects are overwritten instead.
        * All objects are validated before any objects are created, so ``rollback`` is unnecessary.
        * A single dataset save and Solr commit are made at the end (optimization!).
        """
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_list_data(request, deserialized)

        if not 'objects' in deserialized:
            raise BadRequest(_("Invalid data sent."))

        bundles = []
        data = []

        dataset = self.get_dataset_from_kwargs(None, **kwargs)

        for object_data in deserialized['objects']:
            bundle = self.build_bundle(data=dict_strip_unicode_keys(object_data), request=request)

            self.is_valid(bundle, request)

            if bundle.errors:
                self.error_response(bundle.errors, request)

            bundles.append(bundle)
            data.append((
                bundle.data['data'],
                bundle.data.get('external_id', None) 
            ))
        
            self.validate_bundle_data(bundle, request, dataset)

        # Because users may have authenticated via headers the request.user may
        # not be a full User instance. To be sure, we fetch one.
        user = UserProxy.objects.get(id=request.user.id)
        
        try:
            solr_rows = dataset.add_many_rows(user, data)
        except DatasetLockedError:
            raise ImmediateHttpResponse(response=http.HttpForbidden(_('Dataset is currently locked by another process.')))

        for bundle, solr_row in zip(bundles, solr_rows):
            bundle.obj = SolrObject(solr_row)

        if not self._meta.always_return_data:
            return http.HttpNoContent()
        else:
            to_be_serialized = {}
            to_be_serialized['objects'] = [self.full_dehydrate(bundle) for bundle in bundles]
            to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)

            return self.create_response(request, to_be_serialized, response_class=http.HttpAccepted)
Exemplo n.º 46
0
    def post_list(self, request, **kwargs):

        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))

        if not self._meta.always_return_data:
            return http.HttpCreated()
        else:
            return self.create_response(request, updated_bundle, response_class=http.HttpCreated)
Exemplo n.º 47
0
    def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        obj = None
        if getattr(fk_resource._meta, 'include_resource_uri', True) and 'resource_uri' in data:
            uri = data['resource_uri']
            err_msg = "Could not find the provided %s object via resource URI '%s'." % (fk_resource._meta.resource_name, uri,)
            try:
                obj = fk_resource.get_via_uri(uri, request=request)
            except ObjectDoesNotExist:
                raise ApiFieldError(err_msg)

        fk_bundle = fk_resource.build_bundle(
            data=data,
            obj=obj,
            request=request
        )

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        unique_keys = {
            k: v
            for k, v in data.items()
            if k == 'pk' or (hasattr(fk_resource, k) and getattr(fk_resource, k).unique)
        }

        # If we have no unique keys, we shouldn't go look for some resource that
        # happens to match other kwargs. In the case of a create, it might be the
        # completely wrong resource.
        # We also need to check to see if updates are allowed on the FK resource.
        if not obj and unique_keys:
            try:
                fk_resource.obj_get(fk_bundle, **data)
            except (ObjectDoesNotExist, NotFound, TypeError):
                try:
                    # Attempt lookup by primary key
                    fk_resource.obj_get(fk_bundle, **unique_keys)
                except (ObjectDoesNotExist, NotFound):
                    pass
            except MultipleObjectsReturned:
                pass

        # If we shouldn't update a resource, or we couldn't find a matching
        # resource we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        fk_bundle = fk_resource.full_hydrate(fk_bundle)
        fk_resource.is_valid(fk_bundle)
        return fk_bundle
Exemplo n.º 48
0
    def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        obj = None
        if getattr(fk_resource._meta, 'include_resource_uri', True) and 'resource_uri' in data:
            uri = data['resource_uri']
            err_msg = "Could not find the provided %s object via resource URI '%s'." % (fk_resource._meta.resource_name, uri,)
            try:
                obj = fk_resource.get_via_uri(uri, request=request)
            except ObjectDoesNotExist:
                raise ApiFieldError(err_msg)

        fk_bundle = fk_resource.build_bundle(
            data=data,
            obj=obj,
            request=request
        )

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        unique_keys = {
            k: v
            for k, v in data.items()
            if k == 'pk' or (hasattr(fk_resource, k) and getattr(fk_resource, k).unique)
        }

        # If we have no unique keys, we shouldn't go look for some resource that
        # happens to match other kwargs. In the case of a create, it might be the
        # completely wrong resource.
        # We also need to check to see if updates are allowed on the FK resource.
        if not obj and unique_keys:
            try:
                fk_resource.obj_get(fk_bundle, skip_errors=True, **data)
            except (ObjectDoesNotExist, NotFound, TypeError):
                try:
                    # Attempt lookup by primary key
                    fk_resource.obj_get(fk_bundle, skip_errors=True, **unique_keys)
                except (ObjectDoesNotExist, NotFound):
                    pass
            except MultipleObjectsReturned:
                pass

        # If we shouldn't update a resource, or we couldn't find a matching
        # resource we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        fk_bundle = fk_resource.full_hydrate(fk_bundle)
        fk_resource.is_valid(fk_bundle)
        return fk_bundle
Exemplo n.º 49
0
    def put_detail(self, request, **kwargs):
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle_custom_class(data=dict_strip_unicode_keys(deserialized), request=request)
        self.is_valid(bundle, request)

        try:
            updated_bundle = self.obj_update(bundle, request=request, pk=kwargs.get('pk'))
            return HttpAccepted()
        except (NotFound, MultipleObjectsReturned):
            updated_bundle = self.obj_create(bundle, request=request, pk=kwargs.get('pk'))
            return HttpCreated(location=self.get_resource_uri(updated_bundle))
Exemplo n.º 50
0
 def post_list(self, request, **kwargs):
     deserialized = self.deserialize(
         request,
         request.raw_post_data,
         format=request.META.get('CONTENT_TYPE', 'application/json'))
     bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
     self.is_valid(bundle, request)
     updated_bundle = self.obj_create(bundle, request=request)
     resp = self.create_response(request, self.full_dehydrate(updated_bundle.obj))
     resp["location"] = self.get_resource_uri(updated_bundle)
     resp.status_code = 201
     return resp
Exemplo n.º 51
0
 def post_list(self, request, **kwargs):
     """Stop making it return standard location header"""
     deserialized = self.deserialize(request,
                                     request.body,
                                     format=request.META.get(
                                         'CONTENT_TYPE',
                                         'application/json'))
     bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                request=request)
     self.is_valid(bundle)
     updated_bundle = self.obj_create(bundle, request=request)
     return HttpCreated(location=updated_bundle.obj.get_absolute_url())
Exemplo n.º 52
0
 def hydrate_address(self, bundle):
     resrc = AddressResource()
     addr = dict((k[5:], v) for k,v in bundle.data.iteritems() \
             if k.startswith('addr_'))
     geo  = dict((k[4:], float(v)) for k,v in bundle.data.iteritems() \
             if k.startswith('geo_'))
     addr.update(geo)
     addrbundle = resrc.build_bundle(obj=api.models.Address,
             data=dict_strip_unicode_keys(addr))
     addrobj = resrc.obj_create(addrbundle).obj
     bundle.obj.address = addrobj
     return bundle
Exemplo n.º 53
0
 def hydrate_address(self, bundle):
     resrc = AddressResource()
     addr = dict((k[5:], v) for k,v in bundle.data.iteritems() \
             if k.startswith('addr_'))
     geo  = dict((k[4:], float(v)) for k,v in bundle.data.iteritems() \
             if k.startswith('geo_'))
     addr.update(geo)
     addrbundle = resrc.build_bundle(obj=api.models.Address,
                                     data=dict_strip_unicode_keys(addr))
     addrobj = resrc.obj_create(addrbundle).obj
     bundle.obj.address = addrobj
     return bundle
Exemplo n.º 54
0
    def build_data_tables_filters(self, filters=None):
        ret = None
        logic = None
        if not filters:
            return None
        for filter in filters:
            value = filter.get('value')
            field_name = filter.get('column')
            filter_type = filter.get('operator')
            if value and filter_type and filter_type:
                if not field_name in ["molregno", "chembl_id", "pref_name", "canonical_smiles", "full_molformula",
                                      "standard_inchi", "standard_inchi_key", "full_mwt"]:
                    continue
                if field_name == "molregno":
                    if not filter_type in ['exact', 'range', 'gt', 'gte', 'lt', 'lte', 'in']:
                        continue
                elif field_name == "chembl_id":
                    if not filter_type in ['exact', 'range', 'in']:
                        continue
                elif field_name == "full_mwt":
                    if not filter_type in ['exact', 'range', 'gt', 'gte', 'lt', 'lte', 'in', 'isnull']:
                        continue
                elif not filter_type in ['exact', 'iexact', 'contains', 'icontains', 'istartswith', 'startswith',
                                         'endswith', 'iendswith', 'isnull']:
                    continue

                if filter_type == 'isnull':
                    if (isinstance(value, basestring) and value.upper == 'TRUE') or \
                       (isinstance(value, (int, bool)) and value):
                        value = True
                    else:
                        value = False

                if field_name in ["canonical_smiles", "standard_inchi", "standard_inchi_key"]:
                    field_name = ('compoundstructures' + LOOKUP_SEP) + field_name
                elif field_name in ["full_molformula",  "full_mwt"]:
                    field_name = ('compoundproperties' + LOOKUP_SEP) + field_name

                qs_filters = {}
                qs_filter = "%s%s%s" % (field_name, LOOKUP_SEP, filter_type)
                qs_filters[qs_filter] = value
                new_filter = Q(**dict_strip_unicode_keys(qs_filters))

                if not ret:
                    ret = new_filter
                else:
                    if logic.upper() == 'AND':
                        ret = ret & new_filter
                    else:
                        ret = ret | new_filter
                logic = filter.get('logic')
        return ret
Exemplo n.º 55
0
    def multi_batch_save(self, request, **kwargs):
        """Save the data which has been cached in Elasticsearch"""

        deserialized = self.deserialize(request,
                                        request.body,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
        deserialized = self.alter_deserialized_detail_data(
            request, deserialized)

        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)
        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request),
                                          bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request),
                                          bundle)

        id = bundle.data["multiplebatch"]
        mb = CBHCompoundMultipleBatch.objects.get(pk=id)
        creator_user = request.user
        try:
            if mb.batch_count < 100:
                #if small batch just do it syncronously
                res = save_multiple_batch(mb, creator_user, session_key)
            else:

                if not bundle.data.get("task_id_for_save", None):

                    mb.created_by = creator_user.username

                    bundle.data["task_id_for_save"] = async (
                        'cbh_chem_api.tasks.save_multiple_batch', mb,
                        creator_user, session_key)

                res = result(bundle.data["task_id_for_save"], wait=10)
            if res is True:
                return self.create_response(request,
                                            bundle,
                                            response_class=http.HttpCreated)
            if (isinstance(res, basestring)):
                raise Exception(res)
            return self.create_response(request,
                                        bundle,
                                        response_class=http.HttpAccepted)
        except:
            print "cleaning up due error during save transaction"
            clean_up_multi_batch(mb, session_key)
            raise
Exemplo n.º 56
0
 def post_list(self, request, **kwargs):
     deserialized = self.deserialize(
         request, request.raw_post_data,
         format=request.META.get('CONTENT_TYPE', 'application/json')
     )
     bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
     self.is_valid(bundle, request)
     post = request.POST.copy()
     post.update(bundle.data)
     request.POST = post
     request._dont_enforce_csrf_checks = True
     response = password_reset(request)
     return HttpCreated(location=response['location'])
Exemplo n.º 57
0
    def delete_reading_list(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        deserialized = self.deserialize(request, request.body,
                                        format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
        try:
            ReadingList.objects.get(id=bundle.data.get("id"), user=request.user).delete()
        except ReadingList.DoesNotExist:
            raise ImmediateHttpResponse(HttpBadRequest('Bad reading list id'))

        return self.create_response(request, {})
Exemplo n.º 58
0
    def resource_from_data(self,
                           fk_resource,
                           data,
                           request=None,
                           related_obj=None,
                           related_name=None,
                           ref_obj_pk=None):
        """
        Given a dictionary-like structure is provided, a fresh related
        resource is created using that data.
        """
        # Try to hydrate the data provided.
        data = dict_strip_unicode_keys(data)
        fk_bundle = fk_resource.build_bundle(data=data, request=request)

        if related_obj:
            fk_bundle.related_obj = related_obj
            fk_bundle.related_name = related_name

        # We need to check to see if updates are allowed on the FK
        # resource. If not, we'll just return a populated bundle instead
        # of mistakenly updating something that should be read-only.
        if not fk_resource.can_update():
            return fk_resource.full_hydrate(fk_bundle)

        try:
            # much ado about nothing? tayfunsen
            if (ref_obj_pk):
                # We should already have all the data we need in bundle.data
                # and so we don't need to send data['pk'] to obj_update.
                #data['pk'] = ref_obj_pk
                #return fk_resource.obj_update(fk_bundle, **data)
                return fk_resource.obj_update(fk_bundle, pk=ref_obj_pk)
            else:
                # if there's no ref_obj_pk, we should not create the object
                # here.
                return fk_resource.full_hydrate(fk_bundle)
        except NotFound:
            try:
                # Attempt lookup by primary key
                lookup_kwargs = dict((k, v) for k, v in data.iteritems()
                                     if getattr(fk_resource, k).unique)

                if not lookup_kwargs:
                    raise NotFound()

                return fk_resource.obj_update(fk_bundle, **lookup_kwargs)
            except NotFound:
                return fk_resource.full_hydrate(fk_bundle)
        except MultipleObjectsReturned:
            return fk_resource.full_hydrate(fk_bundle)
Exemplo n.º 59
0
    def build_related_resource(self, value):
        """
        Used to ``hydrate`` the data provided. If just a URL is provided,
        the related resource is attempted to be loaded. If a
        dictionary-like structure is provided, a fresh resource is
        created.
        """
        self.fk_resource = self.to_class()

        # Try to hydrate the data provided.
        value = dict_strip_unicode_keys(value)
        self.fk_bundle = Bundle(data=value)

        return self.fk_resource.full_hydrate(self.fk_bundle)