Exemplo n.º 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
Exemplo n.º 2
0
    def test_update_default_phone_number_returns_error_if_invalid_format(self):
        bundle = Bundle()
        bundle.obj = self.user
        bundle.data = {"default_phone_number": ["50253311399"]}

        errors = CommCareUserResource._update(bundle)

        self.assertIn('default_phone_number must be a string', errors)
Exemplo n.º 3
0
    def test_update_unknown_fields_returns_error(self):
        bundle = Bundle()
        bundle.obj = self.user
        bundle.data = {"id": 'updated-id'}

        errors = CommCareUserResource._update(bundle)
        self.assertIn("Attempted to update unknown or non-editable field 'id'",
                      errors)
Exemplo n.º 4
0
    def hydrate_lang(self, bundle):
        translated_bundle = Bundle()
        translation_resource = I4pProjectTranslationEditResource()

        for language_code, language_data in bundle.data["lang"].iteritems():
            if language_code not in dict(LANGUAGES):
                continue
            translated_bundle.data = language_data
            translated_bundle.obj = bundle.obj.translate(language_code)
            translation_resource.obj_create(translated_bundle)

        return bundle
Exemplo n.º 5
0
    def hydrate_lang(self, bundle):
        translated_bundle = Bundle()
        translation_resource = I4pProjectTranslationEditResource()

        for language_code, language_data in bundle.data['lang'].iteritems():
            if language_code not in dict(LANGUAGES):
                continue
            translated_bundle.data = language_data
            translated_bundle.obj = bundle.obj.translate(language_code)
            translation_resource.obj_create(translated_bundle)

        return bundle
Exemplo n.º 6
0
    def test_update_password_with_weak_passwords_returns_error_if_strong_option_on(
            self):
        self.domain_obj.strong_mobile_passwords = True
        self.domain_obj.save()

        bundle = Bundle()
        bundle.obj = self.user
        bundle.data = {"password": '******'}

        errors = CommCareUserResource._update(bundle)

        expected_error_message = 'Password is not strong enough. Try making your password more complex.'
        self.assertIn(expected_error_message, errors)
Exemplo n.º 7
0
    def process(self):
        # Apply envelopes only to HttpResponse returning JSON
        is_eligible = False

        if self.response is None and self.content is None:
            is_eligible = False
            logger.warning('Envelope initialized without response or raw content')
        elif self.content and isinstance(self.content, dict):
            if not(set(['meta', 'data']) < set(self.content.keys())):
                is_eligible = True
            else:
                logger.warning('Attempting to envelope response that is already enveloped')

            if is_eligible:
                self.update_data(self.content)
        elif self.response:
            content_type = self.response._headers.get('content-type', None)
            if content_type is not None and 'json' in content_type[1]:
                original_response_content = json.loads(self.response.content)

                if 'meta' not in original_response_content or 'data' not in original_response_content:
                    is_eligible = True
                else:
                    logger.warning('Attempting to envelope response that is already enveloped')

                if is_eligible:
                    # Load data depending on whether its a list of object or a single object
                    if 'meta' in original_response_content and 'objects' in original_response_content:
                        self.response_data['meta']['pagination'] = original_response_content['meta']
                        self.update_data(original_response_content['objects'])
                    else:
                        self.update_data(original_response_content)
        else:
            logger.warning('Response or data can not be enveloped')

        if is_eligible:
            # Load form errors if present
            if self.validation is not None and isinstance(self.validation, FormValidation):
                bundle = Bundle()
                bundle.data = self.response_data['data']
                form_errors = self.validation.is_valid(bundle)
                if form_errors:
                    self.add_errors('form', form_errors)
                    self.set_status(400)

            self.is_modified = True
        else:
            logger.warning('Response or data can not be enveloped')

        self.is_processed = True
Exemplo n.º 8
0
    def test_update_user_data_returns_error_if_profile_conflict(self):
        bundle = Bundle()
        bundle.obj = self.user
        bundle.data = {
            'user_data': {
                PROFILE_SLUG: self.profile.id,
                'conflicting_field': 'no'
            }
        }

        errors = CommCareUserResource._update(bundle)

        self.assertIn(
            'metadata properties conflict with profile: conflicting_field',
            errors)
Exemplo n.º 9
0
Arquivo: api.py Projeto: catami/catami
    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)
Exemplo n.º 10
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 = {}
        #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)