Example #1
0
 def save(self, *args, **kwargs):
     '''
     Save the model and then create the image that we need.
     '''
     refresh = kwargs.pop('refresh', True)
     if self.default:
         # If this one has default checked, turn off the default for
         # other instances - there can be only one!
         for m in MapColorStyle.objects.filter(default=True):
             if m.pk != self.pk:
                 m.default = False
                 m.save(refresh=False)
     if not self.pk:
         super(MapColorStyle, self).save(*args, **kwargs)
     if refresh:
         legend = LegendGenerator(color_format=self.name,
                                  min_value=0, max_value=255)
         im = legend.generateSampleRamp()
         image_file = StringIO.StringIO()
         im.save(image_file, format='png')
         image_file.seek(0, os.SEEK_END)
         len = image_file.tell()
         image_file.seek(0)
         if self.ramp_graphic:
             if os.path.exists(self.ramp_graphic.path):
                 os.unlink(self.ramp_graphic.path)
         self.ramp_graphic = InMemoryUploadedFile(
             image_file, None, 'ramp_graphic_{0}.png'.format(
                 self.pk,), 'image/png', len, None)
     super(MapColorStyle, self).save(*args, **kwargs)
Example #2
0
 def save(self, *args, **kwargs):
     '''
     Save the model and then create the image that we need.
     '''
     refresh = kwargs.pop('refresh', True)
     if self.default:
         # If this one has default checked, turn off the default for
         # other instances - there can be only one!
         for m in MapColorStyle.objects.filter(default=True):
             if m.pk != self.pk:
                 m.default = False
                 m.save(refresh=False)
     if not self.pk:
         super(MapColorStyle, self).save(*args, **kwargs)
     if refresh:
         legend = LegendGenerator(color_format=self.name,
                                  min_value=0,
                                  max_value=255)
         im = legend.generateSampleRamp()
         image_file = StringIO.StringIO()
         im.save(image_file, format='png')
         image_file.seek(0, os.SEEK_END)
         len = image_file.tell()
         image_file.seek(0)
         if self.ramp_graphic:
             if os.path.exists(self.ramp_graphic.path):
                 os.unlink(self.ramp_graphic.path)
         self.ramp_graphic = InMemoryUploadedFile(
             image_file, None, 'ramp_graphic_{0}.png'.format(self.pk, ),
             'image/png', len, None)
     super(MapColorStyle, self).save(*args, **kwargs)
Example #3
0
def handleWMSRequest(request, datafile):
    get_uc = dict((k.upper(), v) for k, v in request.GET.iteritems())
    style_field = legend = None
    raster = (datafile.geom_type == 99)
    style_field = get_uc.get('STYLE_FIELD', datafile.result_field or None)
    if raster:
        if datafile.field_attributes.keys() > 0:
            style_field = '1'
    legend_units = get_uc.get('LEGEND_UNITS', None)
    reverse = get_uc.get('REVERSE', 'false')
    if reverse.lower() in ('true', 't', '1'):
        reverse = True
    else:
        reverse = False
    ramp = get_uc.get('RAMP', 0)
    attributes = datafile.field_attributes
    if style_field == datafile.result_field:
        legend_units = datafile.result_field_units
    if style_field and style_field not in attributes:
        logger.error(
            'Field specified (%s) does not exist (%s): %s.',
            style_field, type(style_field),
            attributes)
        return HttpResponseBadRequest(
            'Specified style field ({0}) does not exist'.format(style_field))
    if style_field:
        field_attributes = attributes[style_field]
        logger.debug(
            'Field attributes for %s are %s',
            style_field,
            field_attributes)
    else:
        field_attributes = {}
    min_result = max_result = None
    values_list = field_attributes.get('values', [])
    if ('type' in field_attributes and
            field_attributes.get('type', None) not in ('text', 'date',)
            and 'values' not in field_attributes):
        min_result = field_attributes['min']
        max_result = field_attributes['max']

    other_features_color = None
    try:
        ramp = int(ramp)
    except Exception as e:
        return HttpResponseBadRequest(
            'Invalid color ramp specified (integer value is required)')
    if ramp:  # Note that 0 means the default ramp
        ramp_lookup_kwargs = {'pk': ramp}
    else:
        ramp_lookup_kwargs = {'default': True}
    try:
        color_ramp_identifier = models.MapColorStyle.objects.get(
            **ramp_lookup_kwargs)
        ramp_id = color_ramp_identifier.pk
        # If we have an enumerated set of values then there is no "other
        # color"
        if 'values' not in field_attributes:
            other_features_color = color_ramp_identifier.other_color
    except Exception as e:
        return HttpResponseBadRequest(
            'Invalid color ramp specified {0}'.format(ramp))

    legend = LegendGenerator(color_ramp_identifier.name,
                             min_value=min_result, max_value=max_result,
                             reverse=reverse,
                             values_list=values_list,
                             units=legend_units,
                             other_features_color=other_features_color,
                             column_type=field_attributes.get('type', None))
    # If there's a values_list then we'll let the WMS server generate the
    # legend, since it would be using discrete colors anyway, and would be better
    # at creating the legend.
    if get_uc.get('REQUEST', '').lower() == 'getlegendgraphic':
        # Round the value to 4 significant digits.
        im = legend.generateLegendGraphic(width=410)
        response = HttpResponse(content_type='image/png')
        im.save(response, 'png')
        return response
    try:
        # Assume that the ramp won't change once it is made, so here we will
        # just use the ramp id and datafile pk to specify a unique WMS
        # service, so we don't need to keep creating WMS services.
        if reverse:
            base_name = 'wms_r_'
        else:
            base_name = 'wms_'
        if 'field_name' in field_attributes:
            mapfile_path = os.path.join(
                datafile.mapfile_path,
                "{0}{1}_ramp_{2}_{3}.map".format(
                    base_name,
                    datafile.pk,
                    ramp_id,
                    field_attributes['field_name']))
        else:
            mapfile_path = os.path.join(
                datafile.mapfile_path, "{0}{1}_ramp_{2}.map".format(
                    base_name, datafile.pk, ramp_id))
        if not os.path.exists(mapfile_path):
            if not os.path.exists(os.path.dirname(mapfile_path)):
                os.makedirs(os.path.dirname(mapfile_path), 0750)
            try:
                mf = generateMapfile(datafile,
                                     style_field=style_field,
                                     # Iterating over the legend object will return the colors
                                     # so we need only pass that into the
                                     # mapfile gen code.
                                     color_values=legend)
                with open(mapfile_path, 'w') as mapfile:
                    mapfile.write(mf)
            finally:
                pass
        # Create the app to call mapserver.
        app = djpaste.CGIApplication(global_conf=None,
                                     script=settings.MAPSERV_PATH,
                                     include_os_environ=True,
                                     query_string=request.META['QUERY_STRING'],
                                     )
        environ = request.META.copy()
        environ['MS_MAPFILE'] = str(mapfile_path)
        return app(request, environ)
    except djpaste.CGIError as e:
        logger.exception(e)
        return HttpResponseBadRequest()
Example #4
0
def handleWMSRequest(request, datafile):
    get_uc = dict((k.upper(), v) for k, v in request.GET.iteritems())
    style_field = legend = None
    raster = (datafile.geom_type == 99)
    style_field = get_uc.get('STYLE_FIELD', datafile.result_field or None)
    logger.info(
        'Style field is %s, attributes are %s (Found: %s), geom %s, raster %s',
        style_field, datafile.field_attributes.keys(), style_field
        in datafile.field_attributes.keys(), datafile.geom_type, raster)
    band = ''
    if raster:
        if datafile.field_attributes:
            if (style_field not in datafile.field_attributes.keys()):
                logger.debug('Requested style_field was %s', style_field)
                style_field = datafile.field_attributes.keys()[0]
                logger.debug('Setting the style field to %s', style_field)
        else:
            logger.error(
                'No style fields found for raster, using default of 1')
            style_field = '1'
        band = '_band_{0}'.format(style_field)
    legend_units = get_uc.get('LEGEND_UNITS', None)
    reverse = get_uc.get('REVERSE', 'false')
    if reverse.lower() in ('true', 't', '1'):
        reverse = True
    else:
        reverse = False
    ramp = get_uc.get('RAMP', 0)
    attributes = datafile.field_attributes
    logger.debug('Units is %s', datafile.units)
    logger.debug('Style field is %s', style_field)
    if datafile.units and style_field in datafile.units:
        legend_units = datafile.units[style_field]
    if style_field and style_field not in attributes:
        logger.error('Field specified (%s) does not exist (%s): %s.',
                     style_field, type(style_field), attributes)
        return HttpResponseBadRequest(
            'Specified style field ({0}) does not exist'.format(style_field))
    if style_field:
        field_attributes = attributes[style_field]
        logger.debug('Field attributes for %s are %s', style_field,
                     field_attributes)
    else:
        field_attributes = {}
    min_result = max_result = None
    values_list = field_attributes.get('values', [])
    if ('type' in field_attributes
            and field_attributes.get('type', None) not in (
                'text',
                'date',
            ) and 'values' not in field_attributes):
        min_result = field_attributes['min']
        max_result = field_attributes['max']

    other_features_color = None
    try:
        ramp = int(ramp)
    except Exception as e:
        return HttpResponseBadRequest(
            'Invalid color ramp specified (integer value is required)')
    if ramp:  # Note that 0 means the default ramp
        ramp_lookup_kwargs = {'pk': ramp}
    else:
        ramp_lookup_kwargs = {'default': True}
    try:
        color_ramp_identifier = models.MapColorStyle.objects.get(
            **ramp_lookup_kwargs)
        ramp_id = color_ramp_identifier.pk
        # If we have an enumerated set of values then there is no "other
        # color"
        if 'values' not in field_attributes:
            other_features_color = color_ramp_identifier.other_color
    except Exception as e:
        return HttpResponseBadRequest(
            'Invalid color ramp specified {0}'.format(ramp))

    legend = LegendGenerator(color_ramp_identifier.name,
                             min_value=min_result,
                             max_value=max_result,
                             reverse=reverse,
                             values_list=values_list,
                             units=legend_units,
                             other_features_color=other_features_color,
                             column_type=field_attributes.get('type', None))
    # If there's a values_list then we'll let the WMS server generate the
    # legend, since it would be using discrete colors anyway, and would be better
    # at creating the legend.
    if get_uc.get('REQUEST', '').lower() == 'getlegendgraphic':
        # Round the value to 4 significant digits.
        im = legend.generateLegendGraphic(width=410)
        response = HttpResponse(content_type='image/png')
        im.save(response, 'png')
        return response
    try:
        # Assume that the ramp won't change once it is made, so here we will
        # just use the ramp id and datafile pk to specify a unique WMS
        # service, so we don't need to keep creating WMS services.
        if reverse:
            base_name = 'wms_r_'
        else:
            base_name = 'wms_'
        if 'field_name' in field_attributes:
            mapfile_path = os.path.join(
                datafile.mapfile_path, "{0}{1}_ramp_{2}_{3}{4}.map".format(
                    base_name, datafile.pk, ramp_id,
                    field_attributes['field_name'], band))
        else:
            mapfile_path = os.path.join(
                datafile.mapfile_path,
                "{0}{1}_ramp_{2}{3}.map".format(base_name, datafile.pk,
                                                ramp_id, band))
        if not os.path.exists(mapfile_path):
            if not os.path.exists(os.path.dirname(mapfile_path)):
                os.makedirs(os.path.dirname(mapfile_path), 0750)
            try:
                mf = generateMapfile(
                    datafile,
                    style_field=style_field,
                    # Iterating over the legend object will return the colors
                    # so we need only pass that into the
                    # mapfile gen code.
                    color_values=legend)
                with open(mapfile_path, 'w') as mapfile:
                    mapfile.write(mf)
            finally:
                pass
        # Create the app to call mapserver.
        app = djpaste.CGIApplication(
            global_conf=None,
            script=settings.MAPSERV_PATH,
            include_os_environ=True,
            query_string=request.META['QUERY_STRING'],
        )
        environ = request.META.copy()
        environ['MS_MAPFILE'] = str(mapfile_path)
        return app(request, environ)
    except djpaste.CGIError as e:
        logger.exception(e)
        return HttpResponseBadRequest()
Example #5
0
        ramp_lookup_kwargs = {'default': True}
    try:
        color_ramp_identifier = models.MapColorStyle.objects.get(
            **ramp_lookup_kwargs)
        ramp_id = color_ramp_identifier.pk
        # If we have an enumerated set of values then there is no "other color"
        if not field_attributes.has_key('values'):
            other_features_color = color_ramp_identifier.other_color
    except Exception, e:
        return HttpResponseBadRequest(
            'Invalid color ramp specified {0}'.format(ramp))

    legend = LegendGenerator(color_ramp_identifier.name,
                             min_value=min_result,
                             max_value=max_result,
                             reverse=reverse,
                             values_list=values_list,
                             units=legend_units,
                             other_features_color=other_features_color,
                             column_type=field_attributes.get('type', None))

    # If there's a values_list then we'll let the WMS server generate the
    # legend, since it would be using discrete colors anyway, and would be better
    # at creating the legend.
    if get_uc.get('REQUEST', '').lower() == 'getlegendgraphic':
        # Round the value to 4 significant digits.
        im = legend.generateLegendGraphic(width=410)
        response = HttpResponse(content_type='image/png')
        im.save(response, 'png')
        return response
    try:
        # Assume that the ramp won't change once it is made, so here we will
Example #6
0
        ramp_lookup_kwargs={'pk': ramp}  
    else:
        ramp_lookup_kwargs={'default': True}
    try:
        color_ramp_identifier=models.MapColorStyle.objects.get(**ramp_lookup_kwargs)
        ramp_id=color_ramp_identifier.pk
        # If we have an enumerated set of values then there is no "other color"
        if not field_attributes.has_key('values'):
            other_features_color=color_ramp_identifier.other_color
    except Exception, e:
        return HttpResponseBadRequest('Invalid color ramp specified {0}'.format(ramp))
    
    legend=LegendGenerator(color_ramp_identifier.name, 
                           min_value=min_result, max_value=max_result, 
                           reverse=reverse,
                           values_list=values_list,
                           units=legend_units,
                           other_features_color=other_features_color,
                           column_type=field_attributes.get('type', None))

    # If there's a values_list then we'll let the WMS server generate the 
    # legend, since it would be using discrete colors anyway, and would be better
    # at creating the legend.
    if get_uc.get('REQUEST', '').lower() == 'getlegendgraphic':
        # Round the value to 4 significant digits.
        im=legend.generateLegendGraphic(width=410)
        response=HttpResponse(content_type='image/png')
        im.save(response, 'png')
        return response
    try:
        # Assume that the ramp won't change once it is made, so here we will