Exemple #1
0
    def save(self):
        """ Implements the save method so this form can be used in regular django views.

            It does the same validation that it usually does for the API, but instead of
            creating a JSON response, it just creates the object and then returns it.
        """
        assert hasattr(self, 'request')
        assert self.type == 'create' or self.type == 'update'

        # Use the form's cleaned_data to create a bundle
        bundle = Bundle()
        bundle.data = self.cleaned_data
        if hasattr(self, 'request'):
            bundle.request = self.request
        if hasattr(self, 'instance'):
            bundle.obj = self.instance

        # Use the resource's methods to save the bundle
        self.resource.request = self.request
        if self.type == 'create':
            bundle = self.resource.obj_create(bundle)
        elif self.type == 'update':
            assert self.request != None
            assert bundle.obj != None
            bundle = self.resource.obj_update(bundle, self.request)

        # Return the object
        return bundle.obj
Exemple #2
0
    def test_vocabulary_validation(self):
        vv = VocabularyValidation()
        request = RequestFactory()
        request.course = self.sample_course

        mock_bundle = Bundle()
        mock_bundle.data['display_name'] = 'Shapes'
        mock_bundle.request = request

        errors = vv.is_valid(mock_bundle)
        self.assertTrue('error_message' in errors)
        self.assertTrue(
            'A Shapes concept exists' in errors['error_message'][0])

        mock_bundle = Bundle()
        mock_bundle.data['display_name'] = 'Patterns'
        mock_bundle.data['object_id'] = self.sample_course.id
        mock_bundle.request = request
        errors = vv.is_valid(mock_bundle)
        self.assertFalse('error_message' in errors)
Exemple #3
0
    def test_vocabulary_validation(self):
        vv = VocabularyValidation()
        request = RequestFactory()
        request.course = self.sample_course

        mock_bundle = Bundle()
        mock_bundle.data['display_name'] = 'Shapes'
        mock_bundle.request = request

        errors = vv.is_valid(mock_bundle)
        self.assertTrue('error_message' in errors)
        self.assertTrue(
            'A Shapes concept exists' in errors['error_message'][0])

        mock_bundle = Bundle()
        mock_bundle.data['display_name'] = 'Patterns'
        mock_bundle.data['object_id'] = self.sample_course.id
        mock_bundle.request = request
        errors = vv.is_valid(mock_bundle)
        self.assertFalse('error_message' in errors)
Exemple #4
0
    def import_layer(self, request, **kwargs):
        """
        Imports a layer
        """
        self.method_check(request, allowed=['post'])

        b = Bundle()
        b.request = request

        try:
            obj = self.obj_get(b, pk=kwargs.get('pk'))
        except UploadLayer.DoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound())

        configuration_options = request.POST.get('configurationOptions')

        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            configuration_options = json.loads(request.body)

        if isinstance(configuration_options,
                      list) and len(configuration_options) == 1:
            configuration_options = configuration_options[0]

        if isinstance(configuration_options, dict):
            self.clean_configuration_options(request, obj,
                                             configuration_options)
            obj.configuration_options = configuration_options
            obj.save()

        if not configuration_options:
            raise ImmediateHttpResponse(
                response=http.HttpBadRequest('Configuration options missing.'))

        request_cookies = request.COOKIES
        uploaded_file = obj.upload.uploadfile_set.first()
        import_result = import_object.delay(
            uploaded_file.id,
            configuration_options=configuration_options,
            request_cookies=request_cookies,
            request_user=request.user)

        # query the db again for this object since it may have been updated during the import
        obj = self.obj_get(b, pk=kwargs.get('pk'))
        obj.task_id = import_result.id
        obj.save()

        return self.create_response(request, {'task': obj.task_id})
Exemple #5
0
    def import_layer(self, request, **kwargs):
        """
        Imports a layer
        """
        self.method_check(request, allowed=['post'])

        b = Bundle()
        b.request = request

        try:
            obj = self.obj_get(b, pk=kwargs.get('pk'))
        except UploadLayer.DoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound())

        configuration_options = request.POST.get('configurationOptions')

        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            configuration_options = json.loads(request.body)

        if isinstance(configuration_options, list) and len(configuration_options) == 1:
            configuration_options = configuration_options[0]

        if isinstance(configuration_options, dict):
            self.clean_configuration_options(request, obj, configuration_options)
            obj.configuration_options = configuration_options
            obj.save()

        if not configuration_options:
            raise ImmediateHttpResponse(response=http.HttpBadRequest('Configuration options missing.'))

        request_cookies = request.COOKIES
        uploaded_file = obj.upload.uploadfile_set.first()
        import_result = import_object.delay(uploaded_file.id, configuration_options=configuration_options, request_cookies=request_cookies, request_user=request.user)

        # query the db again for this object since it may have been updated during the import
        obj = self.obj_get(b, pk=kwargs.get('pk'))
        obj.task_id = import_result.id
        obj.save()

        return self.create_response(request, {'task': obj.task_id})
Exemple #6
0
 def dehydrate(self, bundle):
     if not bundle.obj or not hasattr(bundle.obj, 'pk'):
         if not self.null:
             raise ApiFieldError("The model '%r' does not have a primary key and can not be d in a ToMany context." % bundle.obj)
         return []
     if not getattr(bundle.obj, self.attribute):
         if not self.null:
             raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't all a null value." % (bundle.obj, self.attribute))
         return []
     self.m2m_resources = []
     m2m_dehydrated = []
     # TODO: Also model-specific and leaky. Relies on there being a
     #       ``Manager`` there.
     # NOTE: only had to remove .all()
     for index, m2m in enumerate(getattr(bundle.obj, self.attribute)):
         m2m.pk = index
         m2m.parent = bundle.obj
         m2m_resource = self.get_related_resource(m2m)
         m2m_bundle = Bundle(obj=m2m)
         self.m2m_resources.append(m2m_resource)
         m2m_bundle.request = bundle.request
         m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))
     return m2m_dehydrated
Exemple #7
0
    def import_layer(self, request, **kwargs):
        """
        Imports a layer
        """
        self.method_check(request, allowed=["post"])

        b = Bundle()
        b.request = request

        try:
            obj = self.obj_get(b, pk=kwargs.get("pk"))
        except UploadLayer.DoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound())

        configuration_options = request.POST.get("configurationOptions")

        if "application/json" in request.META.get("CONTENT_TYPE", ""):
            configuration_options = json.loads(request.body)

        if isinstance(configuration_options, dict):
            obj.configuration_options = configuration_options
            obj.save()
            configuration_options = [configuration_options]

        if not configuration_options:
            raise ImmediateHttpResponse(response=http.HttpBadRequest("Configuration options missing."))

        uploaded_file = obj.upload.uploadfile_set.first()
        import_result = import_object.delay(uploaded_file.id, configuration_options=configuration_options)

        # query the db again for this object since it may have been updated during the import
        obj = self.obj_get(b, pk=kwargs.get("pk"))
        obj.task_id = import_result.id
        obj.save()

        return self.create_response(request, {"task": obj.task_id})
Exemple #8
0
    def image_upload(self, request, **kwargs):
        """
        Special handler function to create a project based on search criteria from images
        """

        json_data = simplejson.loads(request.body)

        deployments = []
        logger.debug("starting web based metadata ingest %s" % json_data["objects"][0]["deployment"])

        # pull the query parameters out
        for i in range(0, len(json_data["objects"]), 1):
            deployment = json_data["objects"][i]["deployment"]
            deployment_id = deployment.split("/")[len(deployment.split("/")) - 2]
            # dp = None
            # if deployment_id in deployments.keys():
            #    dp = deployments[deployment_id]
            # else:
            #    dp = Deployment.objects.filter(id=int(deployment_id))

            # create the Image
            image_bundle = Bundle()
            image_bundle.request = request

            image_name = json_data["objects"][i]["image_name"]
            date_time = json_data["objects"][i]["date_time"]
            position = json_data["objects"][i]["position"]
            depth = json_data["objects"][i]["depth"]
            depth_uncertainty = json_data["objects"][i]["depth_uncertainty"]
            dpc = None
            if depth_uncertainty is not None and depth_uncertainty != "null":
                dpc = float(depth_uncertainty)
            image_bundle.data = dict(
                deployment=deployment,
                image_name=image_name,
                date_time=date_time,
                position=position,
                depth=depth,
                depth_uncertainty=dpc,
            )
            new_image = self.obj_create(image_bundle)

            # create Measurement
            temperature = json_data["objects"][i]["temperature"]
            temperature_unit = json_data["objects"][i]["temperature_unit"]
            salinity = json_data["objects"][i]["salinity"]
            salinity_unit = json_data["objects"][i]["salinity_unit"]
            pitch = json_data["objects"][i]["pitch"]
            pitch_unit = json_data["objects"][i]["pitch_unit"]
            roll = json_data["objects"][i]["roll"]
            roll_unit = json_data["objects"][i]["roll_unit"]
            yaw = json_data["objects"][i]["yaw"]
            yaw_unit = json_data["objects"][i]["yaw_unit"]
            altitude = json_data["objects"][i]["altitude"]
            altitude_unit = json_data["objects"][i]["altitude_unit"]

            measurement_bundle = Bundle()
            measurement_bundle.request = request
            measurement_bundle.data = dict(
                image="/api/dev/image/" + str(new_image.obj.id) + "/",
                temperature=temperature,
                temperature_unit=temperature_unit,
                salinity=salinity,
                salinity_unit=salinity_unit,
                pitch=pitch,
                pitch_unit=pitch_unit,
                roll=roll,
                roll_unit=roll_unit,
                yaw=yaw,
                yaw_unit=yaw_unit,
                altitude=altitude,
                altitude_unit=altitude_unit,
            )

            new_measurement = MeasurementsResource().obj_create(measurement_bundle)

            # create camera
            angle = json_data["objects"][i]["angle"]
            name = json_data["objects"][i]["name"]

            camera_bundle = Bundle()
            camera_bundle.request = request
            camera_bundle.data = dict(
                image="/api/dev/image/" + str(new_image.obj.id) + "/", name=name, angle=int(angle)
            )

            new_camera = CameraResource().obj_create(camera_bundle)

            deployment_response = {"image_name": image_name, "image_uri": "/api/dev/image/" + str(new_image.obj.id)}

            deployments.append(deployment_response)

        logger.debug("finished web based metadata ingest %s" % json_data["objects"][0]["deployment"])

        response = HttpResponse(content_type="application/json")
        response.content = json.dumps(deployments)

        return response

        return self.create_response(request, "Not all fields were provided.", response_class=HttpBadRequest)
    def image_upload(self, request, **kwargs):
        """
        Special handler function to create a project based on search criteria from images
        """

        json_data = simplejson.loads(request.body)
        deployments = {}
        #pull the query parameters out
        for i in range(0, len(json_data['objects']),1):           
            deployment = json_data['objects'][i]['deployment']             
            deployment_id = deployment.split('/')[len(deployment.split('/'))-2]
            #dp = None
            #if deployment_id in deployments.keys():
            #    dp = deployments[deployment_id]
            #else:
            #    dp = Deployment.objects.filter(id=int(deployment_id))


            #create the Image
            image_bundle = Bundle()
            image_bundle.request = request

            image_name = json_data['objects'][i]['image_name']
            date_time = json_data['objects'][i]['date_time']
            position = json_data['objects'][i]['position']
            depth = json_data['objects'][i]['depth']
            depth_uncertainty = json_data['objects'][i]['depth_uncertainty']
            dpc = None
            if (depth_uncertainty is not None and depth_uncertainty != 'null'):    
                dpc = float(depth_uncertainty)           
            image_bundle.data = dict(deployment=deployment, image_name=image_name, 
                                     date_time=date_time, position=position, depth=depth, 
                                     depth_uncertainty=dpc)
            new_image = self.obj_create(image_bundle)   
                  
            #create Measurement
            temperature = json_data['objects'][i]['temperature']
            temperature_unit = json_data['objects'][i]['temperature_unit']
            salinity = json_data['objects'][i]['salinity']
            salinity_unit = json_data['objects'][i]['salinity_unit']
            pitch = json_data['objects'][i]['pitch']
            pitch_unit = json_data['objects'][i]['pitch_unit']
            roll = json_data['objects'][i]['roll']
            roll_unit = json_data['objects'][i]['roll_unit']
            yaw = json_data['objects'][i]['yaw']
            yaw_unit = json_data['objects'][i]['yaw_unit']
            altitude = json_data['objects'][i]['altitude']
            altitude_unit = json_data['objects'][i]['altitude_unit']

            measurement_bundle = Bundle()
            measurement_bundle.request = request
            measurement_bundle.data = dict(image='/api/dev/image/'+str(new_image.obj.id)+'/',
                                           temperature=temperature,
                                           temperature_unit=temperature_unit,
                                           salinity=salinity,
                                           salinity_unit=salinity_unit,
                                           pitch=pitch,
                                           pitch_unit=pitch_unit,
                                           roll=roll,
                                           roll_unit=roll_unit,
                                           yaw=yaw,
                                           yaw_unit=yaw_unit,
                                           altitude=altitude,
                                          altitude_unit=altitude_unit) 

            new_measurement = MeasurementsResource().obj_create(measurement_bundle)   
            
            #create camera
            angle = json_data['objects'][i]['angle']
            name = json_data['objects'][i]['name']

            camera_bundle = Bundle()
            camera_bundle.request = request
            camera_bundle.data = dict(image='/api/dev/image/'+str(new_image.obj.id)+'/',
                                      name=name,
                                      angle=int(angle))

            new_camera = CameraResource().obj_create(camera_bundle) 

        response = HttpResponse(content_type='application/json')        
        return response

        return self.create_response(request, "Not all fields were provided.", response_class=HttpBadRequest)