Beispiel #1
0
    def post_detail(self, request, **kwargs):
        try:
            deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        except Exception:
            return HttpBadRequest()
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))

        # action: generate api key for particular user
        if (bundle.data.has_key('action')) & (bundle.data.get('action')=='generate_api_key'):
            return api.utils.generate_api_key(request, kwargs.get('pk'))

        # clean users api key
        if (bundle.data.has_key('action')) & (bundle.data.get('action')=='clean_api_key'):
            return api.utils.clean_api_key(request, kwargs.get('pk'))

        # action: add user to group
        if (bundle.data.has_key('action')) & bundle.data.has_key('group') & (bundle.data.get('action')=='add_to_group'):
            #print GroupResource().get_via_uri(bundle.data.get('group'))
            User.objects.get(id=kwargs.get('pk')).groups.add(GroupResource().get_via_uri(bundle.data.get('group')))

        # action: remove user from the group
        if (bundle.data.has_key('action')) & bundle.data.has_key('group') & (bundle.data.get('action')=='remove_from_group'):
            User.objects.get(id=kwargs.get('pk')).groups.remove(GroupResource().get_via_uri(bundle.data.get('group')))


        return HttpResponse(status=204)
    def post_list(self, request, **kwargs):
        """
        Creates a new resource/object with the provided data.
        """
        try:
            body = request.body
        except Exception:  # pylint: disable=I0011,W0703
            body = None
        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)

        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 post_list(self, request, **kwargs):
        """
        Creates a new resource/object with the provided data.
        """
        try:
            body = request.body
        except Exception:  # pylint: disable=I0011,W0703
            body = None
        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)

        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)
Beispiel #4
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', '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(',')

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

        return dict_strip_unicode_keys(qs_filters)
Beispiel #5
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)
Beispiel #6
0
 def put_detail(self, request, **kwargs):
     try:
         deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
     except Exception:
         return HttpBadRequest()
     deserialized = self.alter_deserialized_detail_data(request, deserialized)
     bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
     self.is_valid(bundle, request)
     if bundle.data.has_key('api_key'):
         return HttpBadRequest()
     self.obj_update(bundle, request=request, pk=kwargs.get('pk')) # updated_bundle = ...
     return HttpAccepted
Beispiel #7
0
    def _get_and_parse(self, scope='', 
                          field_definition_scope='fields.field'):
        '''
        non-cached Query the metahash table for data identified by "scope", 
        and fields defined by "field_definition_scope"
            e.g. "fields.screensaveruser", or "fields.screen"
        field_definition_scope - also defines what is in the the json_field for 
        this hash;
            e.g. "fields.field", or "fields.resource, or fields.vocabulary"
        '''
        logger.debug(
            'get_and_parse table field definitions for scope: %r, fds: %r',
            scope, field_definition_scope)
        # try to make clear that the field definitions, though stored in the 
        # metahash as well, could be in a separate table
        field_definition_table = MetaHash.objects.all().filter(
            scope=field_definition_scope)
        if not field_definition_table:
            logger.warn('field definitions not found for: %r',
                field_definition_scope)
            return {}
        logger.debug('field_definition_table: %r', field_definition_table)
        # the objects themselves are stored in the metahash table as well
        unparsed_objects = \
            MetaHash.objects.all().filter(scope=scope).order_by('ordinal')
        logger.debug('unparsed_objects: %r', unparsed_objects)
        parsed_objects = OrderedDict()
        for unparsed_object in unparsed_objects:
            parsed_object = {}
            # only need the key from the field definition table
            for field_key in [ x.key for x in field_definition_table]:  
                parsed_object.update(
                    { field_key : unparsed_object.get_field(field_key) })
            
            # NOTE: choices for the "vocabulary_scope_ref" are being stored 
            # here for convenience
            
            if parsed_object.get(u'vocabulary_scope_ref'):
                vocab_ref = parsed_object['vocabulary_scope_ref']
                parsed_object['choices'] = [
                    x.key for x in Vocabulary.objects.all().filter(
                        scope=vocab_ref)]
            
            parsed_objects[unparsed_object.key] = \
                dict_strip_unicode_keys(parsed_object)

        return parsed_objects
Beispiel #8
0
    def _get_and_parse(self, scope='', field_definition_scope='fields.field'):
        '''
        non-cached Query the metahash table for data identified by "scope", 
        and fields defined by "field_definition_scope"
            e.g. "fields.screensaveruser", or "fields.screen"
        field_definition_scope - also defines what is in the the json_field for 
        this hash;
            e.g. "fields.field", or "fields.resource, or fields.vocabulary"
        '''
        logger.debug(
            'get_and_parse table field definitions for scope: %r, fds: %r',
            scope, field_definition_scope)
        # try to make clear that the field definitions, though stored in the
        # metahash as well, could be in a separate table
        field_definition_table = MetaHash.objects.all().filter(
            scope=field_definition_scope)
        if not field_definition_table:
            logger.warn('field definitions not found for: %r',
                        field_definition_scope)
            return {}
        logger.debug('field_definition_table: %r', field_definition_table)
        # the objects themselves are stored in the metahash table as well
        unparsed_objects = \
            MetaHash.objects.all().filter(scope=scope).order_by('ordinal')
        logger.debug('unparsed_objects: %r', unparsed_objects)
        parsed_objects = OrderedDict()
        for unparsed_object in unparsed_objects:
            parsed_object = {}
            # only need the key from the field definition table
            for field_key in [x.key for x in field_definition_table]:
                parsed_object.update(
                    {field_key: unparsed_object.get_field(field_key)})

            # NOTE: choices for the "vocabulary_scope_ref" are being stored
            # here for convenience

            if parsed_object.get(u'vocabulary_scope_ref'):
                vocab_ref = parsed_object['vocabulary_scope_ref']
                parsed_object['choices'] = [
                    x.key
                    for x in Vocabulary.objects.all().filter(scope=vocab_ref)
                ]

            parsed_objects[unparsed_object.key] = \
                dict_strip_unicode_keys(parsed_object)

        return parsed_objects
Beispiel #9
0
    def post_detail(self, request, **kwargs):
        try:
            deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        except Exception:
            return HttpBadRequest()
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))

        # action: add user to group
        if (bundle.data.has_key('action')) & bundle.data.has_key('user') & (bundle.data.get('action')=='add_user'):
            Group.objects.get(id=kwargs.get('pk')).user_set.add(UserResource().get_via_uri(bundle.data.get('user')))

        # action: remove user from the group
        if (bundle.data.has_key('action')) & bundle.data.has_key('user') & (bundle.data.get('action')=='remove_user'):
            Group.objects.get(id=kwargs.get('pk')).user_set.remove(UserResource().get_via_uri(bundle.data.get('user')))

        return HttpResponse(status=204)
Beispiel #10
0
    def post_list(self, request, **kwargs):
        try:
            deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        except Exception:
            return HttpBadRequest()
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))

        # action: generate api key for particular user
        if (bundle.data.has_key('action')) & (bundle.data.get('action')=='generate_api_key') & (bundle.data.has_key('userid')):
            return api.utils.generate_api_key(request, bundle.data.get('userid'))

        # clean users api key
        if (bundle.data.has_key('action')) & (bundle.data.get('action')=='clean_api_key') & (bundle.data.has_key('userid')):
            return api.utils.clean_api_key(request, bundle.data.get('userid'))

        return HttpResponse(status=204)
Beispiel #11
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')
        )
        deserialized = self.alter_deserialized_list_data(request, deserialized)
        bundle = ResultBundle(**dict_strip_unicode_keys(deserialized))
        self.is_valid(bundle, request)
        updated_bundle = self.obj_create(bundle, request=request)
        return HttpCreated(location=self.get_resource_uri(updated_bundle))
Beispiel #12
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')
        )
        deserialized = self.alter_deserialized_list_data(request, deserialized)
        bundle = ResultBundle(**dict_strip_unicode_keys(deserialized))
        self.is_valid(bundle, request)
        updated_bundle = self.obj_create(bundle, request=request)
        return HttpCreated(location=self.get_resource_uri(updated_bundle))
Beispiel #13
0
    def post_list(self, request, **kwargs):
        deserialized = self.deserialize(request, request.raw_post_data,
            format=request.META.get('CONTENT_TYPE', 'application/json'))

        print deserialized

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

        self.is_valid(bundle, request)

        bundle.obj = self._meta.object_class()

        for key, value in kwargs.items():
            setattr(bundle.obj, key, value)

        updated_bundle = self.full_hydrate(bundle)

        location = self.get_resource_uri(updated_bundle)

        return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)