예제 #1
0
    def handle_field(self, obj, field_name):
        if isinstance(obj, Model):
            value = getattr(obj, field_name)
        elif isinstance(obj, dict):
            value = obj[field_name]
        else:
            # Only supports dicts and models, not lists (e.g. values_list)
            return

        # ignore other geometries, only one geometry per feature
        if field_name == self.geometry_field:
            # this will handle GEOSGeometry objects and string representations (e.g. ewkt, bwkt)
            try:
                self._current['geometry'] = GEOSGeometry(value)
            # if the geometry couldn't be parsed, we can't generate valid geojson
            except ValueError:
                raise SerializationError(
                    'The field ["%s", "%s"] could not be parsed as a valid geometry'
                    % (self.geometry_field, value))

        elif self.properties and \
            field_name in self.properties:
            # set the field name to the key's value mapping in self.properties
            if isinstance(self.properties, dict):
                property_name = self.properties[field_name]
                self._current['properties'][property_name] = value
            else:
                self._current['properties'][field_name] = value

        elif not self.properties:
            self._current['properties'][field_name] = value
예제 #2
0
파일: geojson.py 프로젝트: yellowcap/django
 def start_serialization(self):
     if not HAS_GDAL:
         # GDAL is needed for the geometry.geojson call
         raise SerializationError("The geojson serializer requires the GDAL library.")
     self._init_options()
     self._cts = {}  # cache of CoordTransform's
     self.stream.write(
         '{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:%d"}},'
         ' "features": [' % self.srs.srid)
예제 #3
0
 def get_dump_object(self, obj):
     data = {
         "type": "Feature",
         "properties": self._current,
     }
     if self._geometry:
         if self._geometry.srid != self.srid:
             # If needed, transform the geometry in the srid of the global geojson srid
             if not HAS_GDAL:
                 raise SerializationError(
                     'Unable to convert geometry to SRID %s when GDAL is not installed.' % self.srid
                 )
             if self._geometry.srid not in self._cts:
                 srs = SpatialReference(self.srid)
                 self._cts[self._geometry.srid] = CoordTransform(self._geometry.srs, srs)
             self._geometry.transform(self._cts[self._geometry.srid])
         data["geometry"] = eval(self._geometry.geojson)
     else:
         data["geometry"] = None
     return data
예제 #4
0
    def serialize(self, q):
        children = []

        for child in q.children:
            if isinstance(child, Q):
                children.append(self.serialize(child))
            else:
                key, value = child

                if isinstance(value, QuerySet):
                    raise SerializationError('QSerializer: QuerySets are not managed')

                if key.endswith('__range') or key.endswith('__in'):
                    value = [self._serialize_value(part) for part in value]
                else:
                    value = self._serialize_value(value)

                children.append((key, value))

        return {'op': 'N' + q.connector if q.negated else q.connector,
                'val': children,
               }
예제 #5
0
    def _handle_geom(self, value):
        """ Geometry processing (in place), depending on options """
        if value is None:
            geometry = None
        elif isinstance(value, dict) and 'type' in value:
            geometry = value
        else:
            if isinstance(value, GEOSGeometry):
                geometry = value
            else:
                try:
                    # this will handle string representations (e.g. ewkt, bwkt)
                    geometry = GEOSGeometry(value)
                except ValueError:
                    # if the geometry couldn't be parsed.
                    # we can't generate valid geojson
                    error_msg = 'The field ["%s", "%s"] could not be parsed as a valid geometry' % (
                        self.geometry_field, value)
                    raise SerializationError(error_msg)

            # Optional force 2D
            if self.options.get('force2d'):
                wkb_w = WKBWriter()
                wkb_w.outdim = 2
                geometry = GEOSGeometry(wkb_w.write(geometry),
                                        srid=geometry.srid)
            # Optional geometry simplification
            simplify = self.options.get('simplify')
            if simplify is not None:
                geometry = geometry.simplify(tolerance=simplify,
                                             preserve_topology=True)
            # Optional geometry reprojection
            if geometry.srid and geometry.srid != self.srid:
                geometry.transform(self.srid)
            # Optional bbox
            if self.options.get('bbox_auto'):
                self._current['bbox'] = geometry.extent

        self._current['geometry'] = geometry