Beispiel #1
0
def __construct_filters(req, config):    
    # get filters if any
    if config['params'].has_key('filter'):
        for filter in config['params']['filter']:
            try: field = config['model']._meta.get_field_by_name(filter['property'])[0]
            except: field = None
            if field and isinstance(field, models.ForeignKey):
                config['filters']['%s__uuid' % filter['property']] = misc.validate_uuid(filter['value'])
                continue
            __handle_filter(config, filter['property'], filter['value']) 
    # query filter
    if config['params'].has_key('query_field') and config['params'].has_key('query') and config['params']['query']:
        __handle_filter(config, config['params']['query_field'], config['params']['query'], '__istartswith')
    # filter by ownership, unless public_view, related_view or anonymous is True
    if not config['anonymous'] and not config['public_view'] and not config['related_view'] and not config['archive']:
        config['filters']['owner'] = req.user
    # filter by given uuid if any
    if config['record_uuid']:
        config['filters']['uuid'] = config['record_uuid']
    # filter by related field
    if config['related_view']:
        config['filters'][config['model'].related_field] = __get_model('Person').objects.getOwn(req.user)
    # filter by related field for archive tables
    if config['archive']:
        config['filters']['owner'] = __get_model('Person').objects.getOwn(req.user).uuid
    # check show_all flag if filters is empty in a GET request
    # otherwise this would return all rows in the table !
    if req.method == 'GET' and not config['filters'] and not config['q_filters'] and \
    (not hasattr(config['model'], 'show_all') or not config['model'].show_all): 
        return HttpResponseNotAllowed('Not Allowed')
    # hide rows marked as deleted. anonymous and archive models doesn't have a deleted field
    if not config['anonymous'] and not config['archive']:
        config['filters']['deleted'] = False
    return config
Beispiel #2
0
def __construct_filters(req, config):
    # get filters if any
    if config['params'].has_key('filter'):
        for filter in config['params']['filter']:
            try:
                field = config['model']._meta.get_field_by_name(
                    filter['property'])[0]
            except:
                field = None
            if field and isinstance(field, models.ForeignKey):
                config['filters']['%s__uuid' %
                                  filter['property']] = misc.validate_uuid(
                                      filter['value'])
                continue
            __handle_filter(config, filter['property'], filter['value'])
    # query filter
    if config['params'].has_key('query_field') and config['params'].has_key(
            'query') and config['params']['query']:
        __handle_filter(config, config['params']['query_field'],
                        config['params']['query'], '__istartswith')
    # filter by ownership, unless public_view, related_view or anonymous is True
    if not config['anonymous'] and not config['public_view'] and not config[
            'related_view'] and not config['archive']:
        config['filters']['owner'] = req.user
    # filter by given uuid if any
    if config['record_uuid']:
        config['filters']['uuid'] = config['record_uuid']
    # filter by related field
    if config['related_view']:
        config['filters'][config['model'].related_field] = __get_model(
            'Person').objects.getOwn(req.user)
    # filter by related field for archive tables
    if config['archive']:
        config['filters']['owner'] = __get_model('Person').objects.getOwn(
            req.user).uuid
    # check show_all flag if filters is empty in a GET request
    # otherwise this would return all rows in the table !
    if req.method == 'GET' and not config['filters'] and not config['q_filters'] and \
    (not hasattr(config['model'], 'show_all') or not config['model'].show_all):
        return HttpResponseNotAllowed('Not Allowed')
    # hide rows marked as deleted. anonymous and archive models doesn't have a deleted field
    if not config['anonymous'] and not config['archive']:
        config['filters']['deleted'] = False
    return config
Beispiel #3
0
def __translate_path(req, config):
    data_path = config['data_path'].strip().split('/')
    config['public_view'] = False
    config['related_view'] = False
    if data_path[0].endswith('_P'):
        config['model_name'] = data_path[0][:-2]
        config['public_view'] = True
    elif data_path[0].endswith('_R'):
        config['model_name'] = data_path[0][:-2]
        config['related_view'] = True
    else:
        config['model_name'] = data_path[0]
    if config['public_view'] and req.method != 'GET':
        return HttpResponseNotAllowed('Not Allowed') 
    try: config['record_uuid'] = misc.validate_uuid(data_path[1])
    except IndexError:
        if req.method == 'GET':
            config['record_uuid'] = None
        else:
            return HttpResponseBadRequest("Bad Request")
    return config
Beispiel #4
0
def __translate_path(req, config):
    data_path = config['data_path'].strip().split('/')
    config['public_view'] = False
    config['related_view'] = False
    if data_path[0].endswith('_P'):
        config['model_name'] = data_path[0][:-2]
        config['public_view'] = True
    elif data_path[0].endswith('_R'):
        config['model_name'] = data_path[0][:-2]
        config['related_view'] = True
    else:
        config['model_name'] = data_path[0]
    if config['public_view'] and req.method != 'GET':
        return HttpResponseNotAllowed('Not Allowed')
    try:
        config['record_uuid'] = misc.validate_uuid(data_path[1])
    except IndexError:
        if req.method == 'GET':
            config['record_uuid'] = None
        else:
            return HttpResponseBadRequest("Bad Request")
    return config
Beispiel #5
0
def __prepare_record_data(req, config):
    # a new record, add uuid and owner
    if not config.has_key('rec'):
        config['rec_data']['uuid'] = config['record_uuid']
        config['rec_data']['owner'] = req.user

    # body
    body_data = {}
    for k, v in config['body'].iteritems():
        if k in settings.RESERVED_MODEL_FIELDS: continue
        try:
            field = config['model']._meta.get_field_by_name(k)[0]
        except:
            if settings.DEBUG:
                logging.debug("UNKNOWN FIELD '%s'" % k)
            return HttpResponseBadRequest("Bad Request")

        if settings.DEBUG:
            logging.debug("BODY FIELD: %s => %s" % (k, field))

        # fk field
        if isinstance(field, models.ForeignKey):
            if v:
                # get uuid
                if isinstance(v, dict):
                    if v.has_key('uuid'):
                        uuid_pk = misc.validate_uuid(v['uuid'])
                    else:
                        if settings.DEBUG:
                            logging.debug("INVALID FKEY DICT VALUE: %s" % v)
                        return HttpResponseBadRequest("Bad Request")
                else:
                    uuid_pk = misc.validate_uuid(v)
                # get record
                m = field.related.parent_model
                try:
                    body_data[k] = m.objects.get_by_natural_key(uuid_pk)
                except ObjectDoesNotExist:
                    if isinstance(v, dict) and hasattr(
                            m,
                            'auto_create_related') and m.auto_create_related:
                        v['owner'] = req.user
                        body_data[k] = m.objects.create(**v)
                    else:
                        if settings.DEBUG:
                            logging.debug("RECORD NOT FOUND: %s/%s" %
                                          (m._meta.object_name, v))
                        raise Http404
            elif field.null:
                body_data[k] = None
            else:
                if settings.DEBUG:
                    logging.debug("FIELD '%s' CANNOT BE NULL" % k)
                return HttpResponseBadRequest("Bad Request")
        # m2m field
        elif isinstance(field, models.ManyToManyField):
            related_model = field.related.parent_model
            if isinstance(v, list):
                config['m2m_data'][field.name] = []
                for i in v:
                    try:
                        related_uuid = misc.validate_uuid(i)
                    except:
                        if settings.DEBUG:
                            logging.debug(
                                'CANNOT FIND UUID IN RELATED FIELD: %s' % i)
                        return HttpResponseBadRequest("Bad Request")
                    try:
                        related_rec = related_model.objects.get_by_natural_key(
                            related_uuid)
                    except ObjectDoesNotExist:
                        if isinstance(i, dict) and hasattr(
                                related_model, 'auto_create_related'
                        ) and related_model.auto_create_related:
                            i['owner'] = req.user
                            related_rec = related_model.objects.create(**i)
                        else:
                            if settings.DEBUG:
                                logging.debug(
                                    "RELATED M2M RECORD NOT FOUND: %s/%s" %
                                    (related_model._meta.object_name,
                                     related_uuid))
                            raise Http404
                    config['m2m_data'][field.name].append(related_rec)
        # related field
        elif isinstance(field, models.related.RelatedObject):
            if v:
                try:
                    related_rec = field.model.objects.get_by_natural_key(
                        misc.validate_uuid(v))
                except ObjectDoesNotExist:
                    if isinstance(v, dict) and hasattr(
                            field.model, 'auto_create_related'
                    ) and field.model.auto_create_related:
                        v['owner'] = req.user
                        related_rec = field.model.objects.create(**v)
                    else:
                        if settings.DEBUG:
                            logging.debug("RELATED RECORD NOT FOUND: %s/%s" %
                                          (field.model._meta.object_name, v))
                        raise Http404
                config['related_field'] = getattr(related_rec,
                                                  field.field.name)
        # plain field
        else:
            body_data[k] = v

    # the client sent no data
    # silently ignore the request...
    if not body_data and not config['m2m_data']:
        if settings.DEBUG:
            logging.debug('W' * 1000)
            logging.debug('PUT REQUEST WITH NO DATA !')
        return HttpResponse()
        #return HttpResponseBadRequest("Bad Request")

    # update config
    config['rec_data'].update(body_data)
    return config
Beispiel #6
0
def __prepare_record_data(req, config):
    # a new record, add uuid and owner
    if not config.has_key('rec'):
        config['rec_data']['uuid'] = config['record_uuid']
        config['rec_data']['owner'] = req.user
    
    # body
    body_data = {}
    for k, v in config['body'].iteritems():
        if k in settings.RESERVED_MODEL_FIELDS: continue
        try: field = config['model']._meta.get_field_by_name(k)[0]
        except:
            if settings.DEBUG:
                logging.debug("UNKNOWN FIELD '%s'" % k)
            return HttpResponseBadRequest("Bad Request")
        
        if settings.DEBUG:
            logging.debug("BODY FIELD: %s => %s" % (k, field))
        
        # fk field
        if isinstance(field, models.ForeignKey):
            if v:
                # get uuid
                if isinstance(v, dict):
                    if v.has_key('uuid'):
                        uuid_pk = misc.validate_uuid(v['uuid'])
                    else:
                        if settings.DEBUG:
                            logging.debug("INVALID FKEY DICT VALUE: %s" % v)
                        return HttpResponseBadRequest("Bad Request")
                else:
                    uuid_pk = misc.validate_uuid(v)
                # get record
                m = field.related.parent_model
                try: body_data[k] = m.objects.get_by_natural_key(uuid_pk)
                except ObjectDoesNotExist:
                    if isinstance(v, dict) and hasattr(m, 'auto_create_related') and m.auto_create_related:
                        v['owner'] = req.user
                        body_data[k] = m.objects.create(**v)
                    else:
                        if settings.DEBUG:
                            logging.debug("RECORD NOT FOUND: %s/%s" % (m._meta.object_name, v))
                        raise Http404
            elif field.null:
                body_data[k] = None
            else:
                if settings.DEBUG:
                    logging.debug("FIELD '%s' CANNOT BE NULL" % k)
                return HttpResponseBadRequest("Bad Request")
        # m2m field
        elif isinstance(field, models.ManyToManyField):
            related_model = field.related.parent_model
            if isinstance(v, list):
                config['m2m_data'][field.name] = []
                for i in v:
                    try:
                        related_uuid = misc.validate_uuid(i)
                    except:
                        if settings.DEBUG:
                            logging.debug('CANNOT FIND UUID IN RELATED FIELD: %s' % i)
                        return HttpResponseBadRequest("Bad Request")
                    try:
                        related_rec = related_model.objects.get_by_natural_key(related_uuid)
                    except ObjectDoesNotExist:
                        if isinstance(i, dict) and hasattr(related_model, 'auto_create_related') and related_model.auto_create_related:
                            i['owner'] = req.user
                            related_rec = related_model.objects.create(**i)
                        else:
                            if settings.DEBUG:
                                logging.debug("RELATED M2M RECORD NOT FOUND: %s/%s" % (related_model._meta.object_name, related_uuid))
                            raise Http404
                    config['m2m_data'][field.name].append(related_rec)
        # related field
        elif isinstance(field, models.related.RelatedObject):
            if v:
                try:
                    related_rec = field.model.objects.get_by_natural_key(misc.validate_uuid(v))
                except ObjectDoesNotExist:
                    if isinstance(v, dict) and hasattr(field.model, 'auto_create_related') and field.model.auto_create_related:
                        v['owner'] = req.user
                        related_rec = field.model.objects.create(**v)
                    else:
                        if settings.DEBUG:
                            logging.debug("RELATED RECORD NOT FOUND: %s/%s" % (field.model._meta.object_name, v))
                        raise Http404
                config['related_field'] = getattr(related_rec, field.field.name) 
        # plain field
        else:
            body_data[k] = v
                        
    # the client sent no data
    # silently ignore the request...
    if not body_data and not config['m2m_data']:
        if settings.DEBUG:
            logging.debug('W'*1000)
            logging.debug('PUT REQUEST WITH NO DATA !')
        return HttpResponse()
        #return HttpResponseBadRequest("Bad Request")
    
    # update config
    config['rec_data'].update(body_data)
    return config