示例#1
0
 def test_various_statuses(self):
     created = HttpCreated(location='http://example.com/thingy/1/')
     self.assertEqual(created.status_code, 201)
     self.assertEqual(created['Location'], 'http://example.com/thingy/1/')
     # Regression.
     created_2 = HttpCreated()
     self.assertEqual(created_2.status_code, 201)
     self.assertEqual(created_2['Location'], '')
     accepted = HttpAccepted()
     self.assertEqual(accepted.status_code, 202)
     no_content = HttpNoContent()
     self.assertEqual(no_content.status_code, 204)
     see_other = HttpSeeOther()
     self.assertEqual(see_other.status_code, 303)
     not_modified = HttpNotModified()
     self.assertEqual(not_modified.status_code, 304)
     bad_request = HttpBadRequest()
     self.assertEqual(bad_request.status_code, 400)
     unauthorized = HttpUnauthorized()
     self.assertEqual(unauthorized.status_code, 401)
     not_found = HttpNotFound()
     self.assertEqual(not_found.status_code, 404)
     not_allowed = HttpMethodNotAllowed()
     self.assertEqual(not_allowed.status_code, 405)
     conflict = HttpConflict()
     self.assertEqual(conflict.status_code, 409)
     gone = HttpGone()
     self.assertEqual(gone.status_code, 410)
     toomanyrequests = HttpTooManyRequests()
     self.assertEqual(toomanyrequests.status_code, 429)
     not_implemented = HttpNotImplemented()
     self.assertEqual(not_implemented.status_code, 501)
示例#2
0
 def obj_delete(self, bundle, **kwargs):
     try:
         data_item = FixtureDataItem.get(kwargs['pk'])
     except ResourceNotFound:
         raise NotFound('Lookup table item not found')
     with CouchTransaction() as transaction:
         data_item.recursive_delete(transaction)
     return ImmediateHttpResponse(response=HttpAccepted())
示例#3
0
    def get_detail(self, request, **kwargs):
        """
            Called by the request dispatcher in case somebody tries to GET a job resource.
            For the frontend, deliver the current job status if pending, or the result.
        """
        basic_bundle = self.build_bundle(request=request)
        try:
            job = self.cached_obj_get(
                bundle=basic_bundle,
                **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpNotFound()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        if job.done():
            if job.exit_code == 0:
                response = {}
                # We deliver the columns layout for the result tables + all
                # global issues
                relative_url = reverse(
                    'results',
                    kwargs={
                        'api_name': 'front',
                        'pk': job.graph.pk,
                        'secret': job.secret})
                # This is a quick fix for dealing with reverse() begind an SSL proxy
                # Normally, Django should consider the X-FORWARDED header inside the reverse()
                # implementation and figure out by itself what the correct base is
                results_url = settings.SERVER + relative_url
                if not job.requires_download:
                    response['columns'] = [
                        {'mData': key, 'sTitle': title} for key, title in job.result_titles]
                    response['axis_titles'] = job.axis_titles()
                    response['static_info'] = job.static_info()
                try:
                    response['issues'] = Result.objects.get(
                        job=job,
                        kind=Result.GRAPH_ISSUES).issues
                except Exception:
                    # no global issues recorded, that's fine
                    pass
                response = HttpResponse(json.dumps(response))
                response["Location"] = results_url
                return response
            else:
                logger.debug("Job is done, but with non-zero exit code.")
                mail_managers(
                    'Job %s for graph %u ended with non-zero exit code %u.' % (
                        job.pk,
                        job.graph.pk,
                        job.exit_code),
                    job.graph.to_xml())
                return HttpApplicationError()
        else:
            # Job is pending, tell this by HTTP return code
            return HttpAccepted()
示例#4
0
    def obj_create(self, bundle, **kwargs):

        lines = bundle.data.get('lines')

        if len(lines) == 1:
            logger.error('error: Arquivo contem apenas a linha de cabecalho.')
            raise ImmediateHttpResponse(
                HttpBadRequest(
                    JsonResponse({
                        'error':
                        'Arquivo contem apenas a linha de cabecalho.'
                    })))
        elif len(lines) < 2:
            logger.error('error: Arquivo importado nao contem registros.')
            raise ImmediateHttpResponse(
                HttpBadRequest(
                    JsonResponse(
                        {'error': 'Arquivo importado nao contem registros.'})))
        ''' Pega cabecalho(linha 0) do CSV '''
        row_names = lines[0].split(";")
        logger.info(
            'Cabecalho(linha 0) do arquivo CSV: {0}.'.format(row_names))
        ''' Retira o cabecalho(linha 0) do CSV '''
        lines = lines[1:len(lines)]
        ''' Cria lista de jsons(chave,valor) a partir das demais linhas do CSV '''
        jsons = []
        for line in lines:
            json_data = {}
            for x, row_name in enumerate(row_names):
                json_data[str(row_name)] = str(line.split(";")[x])
            jsons.append(json_data)

        for i, json in enumerate(jsons):
            logger.info(
                'JSON gerado a partir da linha {0} do arquivo CSV: {1}.'.
                format(i + 2, json))

        raise ImmediateHttpResponse(
            HttpAccepted(JsonResponse({'lines': jsons})))
示例#5
0
    def obj_update(self, bundle, **kwargs):
        try:
            # Allows BFRS and SSS to perform update only if permitted
            if is_external_user(bundle.request.user):
                raise ImmediateHttpResponse(response=HttpUnauthorized())

            if not can_maintain_data(
                    bundle.request.user
            ) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
                raise ImmediateHttpResponse(response=HttpUnauthorized())

            if bundle.request.GET.has_key(
                    'checkpermission'
            ) and bundle.request.GET['checkpermission'] == 'true':
                #this is a permission checking request,return directly.
                raise ImmediateHttpResponse(response=HttpAccepted())

            self.full_hydrate(bundle)
            #invalidate current bushfire if required.
            bundle.obj, invalidated = invalidate_bushfire(
                bundle.obj, bundle.request.user) or (bundle.obj, False)

            if not invalidated:
                bundle.obj.save()

            if bundle.data.has_key('area'):
                if (bundle.data.get('area') or {}).get('total_area') == None:
                    #no burning area,
                    bundle.obj.tenures_burnt.all().delete()
                else:
                    #print("Clear tenure burnt data")
                    if bundle.obj.report_status != Bushfire.STATUS_INITIAL and bundle.data[
                            'area'].get('layers'):
                        #report is not a initial report, and has area burnt data, save it.
                        #print("Populate new tenure burnt data")
                        update_areas_burnt(bundle.obj, bundle.data['area'])
                    else:
                        #report is a initial report,or has no area burnt data. clear the existing area burnt data
                        #area burnt data is unavailable for initial report
                        bundle.obj.tenures_burnt.all().delete()

            #save plantations
            if bundle.data.has_key("plantations"):
                #need to update plantations
                if bundle.data.get("plantations"):
                    #has plantation data
                    BushfireProperty.objects.update_or_create(
                        bushfire=bundle.obj,
                        name="plantations",
                        defaults={
                            "value": json.dumps(bundle.data.get("plantations"))
                        })
                else:
                    #no plantation data,remove the plantations data from table
                    BushfireProperty.objects.filter(
                        bushfire=bundle.obj, name="plantations").delete()

            if bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
                if bundle.obj.fire_boundary.contains(bundle.obj.origin_point):
                    # if bushfire has been authorised, update snapshot and archive old snapshot
                    serialize_bushfire('final', 'SSS Update', bundle.obj)
                else:
                    if bundle.obj.is_reviewed:
                        update_status(
                            bundle.request,
                            bundle.obj,
                            "delete_review",
                            action_desc=
                            "Delete review because origin point is outside of fire boundary after uploading from SSS",
                            action_name="Upload")

                    if bundle.obj.is_final_authorised:
                        update_status(
                            bundle.request,
                            bundle.obj,
                            "delete_final_authorisation",
                            action_desc=
                            "Delete final auth because origin point is outside of fire boundary after uploading from SSS",
                            action_name="Upload")

                #print("serizlie bushfire")

            if invalidated:
                raise ImmediateHttpResponse(response=JsonResponse(
                    {
                        "id": bundle.obj.id,
                        "fire_number": bundle.obj.fire_number
                    },
                    status=280))
            else:
                return bundle
        except:
            if bundle.request.GET.has_key(
                    'checkpermission'
            ) and bundle.request.GET['checkpermission'] == 'true':
                #for permission checking purpose, don't log the exception in log file.
                pass
            else:
                traceback.print_exc()
            raise
示例#6
0
    def obj_update(self, bundle, **kwargs):

        if bundle.request.GET.has_key('checkpermission') and bundle.request.GET['checkpermission'] == 'true':
            # Allows SSS to perform permission check
            if is_external_user(bundle.request.user) or \
               (not can_maintain_data(bundle.request.user) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED):
                raise ImmediateHttpResponse(response=HttpUnauthorized())
            else:
                raise ImmediateHttpResponse(response=HttpAccepted())

        # Allows BFRS and SSS to perform update only if permitted
        if is_external_user(bundle.request.user):
            return bundle

        if not can_maintain_data(bundle.request.user) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
            raise ImmediateHttpResponse(response=HttpUnauthorized())

        self.full_hydrate(bundle)
        #bundle.obj.sss_data = json.dumps(bundle.data)
        sss_data = bundle.data
        #import ipdb; ipdb.set_trace()
        if sss_data.has_key('fire_boundary'):
            sss_data.pop('fire_boundary')
        #if sss_data.has_key('area') and sss_data.get('area').has_key('tenure_area'):
        #    sss_data.get('area').pop('tenure_area') # necessary for the initial create stagei for display in form, since object not yet saved
        bundle.obj.sss_data = json.dumps(sss_data)

        if bundle.data.has_key('tenure_ignition_point') and bundle.data['tenure_ignition_point'] and \
            bundle.data['tenure_ignition_point'].has_key('category') and bundle.data['tenure_ignition_point']['category']:
            try:
                bundle.obj.tenure = Tenure.objects.get(name__istartswith=bundle.data['tenure_ignition_point']['category'])
            except:
                bundle.obj.tenure = Tenure.objects.get(name__iendswith='other')
        elif bundle.data.has_key('tenure_ignition_point') and not bundle.data['tenure_ignition_point']:
            bundle.obj.tenure = Tenure.objects.get(name__iendswith='other')

        if bundle.data.has_key('area') and bundle.data['area'].has_key('layers') and bundle.data['area']['layers']:
            update_areas_burnt(bundle.obj, bundle.data['area']['layers'])


        if bundle.data.has_key('area') and bundle.data['area'].has_key('total_area') and bundle.data['area']['total_area']:
            if bundle.obj.report_status < Bushfire.STATUS_INITIAL_AUTHORISED:
                bundle.obj.area_unknown = False
                initial_area = round(float(bundle.data['area']['total_area']), 2)
                bundle.obj.initial_area = initial_area if initial_area > 0 else 0.01
            else:
                bundle.obj.area_limit = False
                area = round(float(bundle.data['area']['total_area']), 2)
                bundle.obj.area = area if area > 0 else 0.01

        if bundle.data.has_key('area') and bundle.data['area'].has_key('other_area') and bundle.data['area']['other_area']:
            other_area = round(float(bundle.data['area']['other_area']), 2)
            bundle.obj.other_area = other_area if other_area > 0 else 0.01

        if bundle.data.has_key('fire_position') and bundle.data['fire_position']:
            # only update if user has not over-ridden
            if not bundle.obj.fire_position_override:
                bundle.obj.fire_position = bundle.data['fire_position']

        if bundle.data.has_key('region_id') and bundle.data.has_key('district_id') and bundle.data['region_id'] and bundle.data['district_id']:
            if bundle.data['district_id'] != bundle.obj.district.id and bundle.obj.report_status == Bushfire.STATUS_INITIAL:
                district = District.objects.get(id=bundle.data['district_id'])
                invalidate_bushfire(bundle.obj, district, bundle.request.user)

        if bundle.obj.report_status >=  Bushfire.STATUS_FINAL_AUTHORISED:
            # if bushfire has been authorised, update snapshot and archive old snapshot
            serialize_bushfire('final', 'SSS Update', bundle.obj)

        bundle.obj.save()
        return bundle