Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props["id"] = product_id
poly = geomet.wkt.loads(props["footprint"])
del props["footprint"]
del props["gmlfootprint"]
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
feature_list.append(geojson.Feature(geometry=poly, id=i, properties=props))
return geojson.FeatureCollection(feature_list)
def from_wkt(s):
"""
Parse a Point geometry from a wkt string and return a new Point object.
"""
if not _HAS_GEOMET:
raise DriverException("Geomet is required to deserialize a wkt geometry.")
try:
geom = wkt.loads(s)
except ValueError:
raise ValueError("Invalid WKT geometry: '{0}'".format(s))
if geom['type'] != 'Point':
raise ValueError("Invalid WKT geometry type. Expected 'Point', got '{0}': '{1}'".format(geom['type'], s))
coords = geom['coordinates']
if len(coords) < 2:
x = y = _nan
else:
x = coords[0]
y = coords[1]
return Point(x=x, y=y)
def _update(self):
"""updates the current row"""
txts = []
values = []
for k,v in self._values.items():
if k.lower() != "objectid" and \
k.lower() != 'shape':
txts.append("%s=?" % k)
values.append(v)
elif k.lower() == 'shape':
if isinstance(v, dict) and "coordinates" not in v:
v = self._header + dumps(v, False)
elif isinstance(v, dict) and "coordinates" in v:
v = self._gpheader + geometwkb.dumps(obj=v)
elif isinstance(v, str):
gj = geometwkt.loads(v)
v = self._gpheader + geometwkb.dumps(obj=gj)
elif isinstance(v, (bytes, bytearray)):
if isinstance(v, (bytearray)):
v = bytes(v)
if len(v) > 2 and \
v[:2] != b'GB':
v = self._gpheader + v
elif v is None:
v = self._gpheader + b'0x000000000000f87f'
else:
raise ValueError(("Shape column must be Esri JSON dictionary, "
"WKT, GeoJSON dictionary, or WKB (bytes)"))
txts.append("%s=?" % k)
values.append(v)
sql = '''UPDATE {table} SET {values} WHERE OBJECTID={oid}'''.format(
table=self._table_name,
"""
if _HASGEOMET == False and geom_format.lower() in ['wkt', 'geojson']:
raise ValueError(("The package `geomet` is required to work with "
"WKT and GeoJSON. Run `pip install geomet` to install."))
if isinstance(row, _Row):
row = row._values
values = None
flds = {fld.lower(): fld for fld in row.keys()}
if 'shape' in flds:
if isinstance(row[flds['shape']], dict) and geom_format.lower() == "esrijson":
row[flds['shape']] = self._gpheader + dumps(row[flds['shape']], False)
elif isinstance(row[flds['shape']], dict) and geom_format.lower() == "geojson":
row[flds['shape']] = self._gpheader + geometwkb.dumps(obj=row[flds['shape']])
elif isinstance(row[flds['shape']], str) and geom_format.lower() == "wkt":
gj = geometwkt.loads(row[flds['shape']])
row[flds['shape']] = self._gpheader + geometwkb.dumps(obj=gj)
elif isinstance(row[flds['shape']], (bytes, bytearray)):
if isinstance(row[flds['shape']], (bytearray)):
row[flds['shape']] = bytes(row[flds['shape']])
if len(row[flds['shape']]) > 2 and \
row[flds['shape']][:2] != b'GB':
row[flds['shape']] = self._gpheader + row[flds['shape']]
elif row[flds['shape']] is None:
row[flds['shape']] = self._gpheader + b'0x000000000000f87f'
else:
raise ValueError(("Shape column must be Esri JSON dictionary, "
"WKT, GeoJSON dictionary, or WKB (bytes)"))
if isinstance(row, dict):
keys = row.keys()
values = [list(row.values())]
elif isinstance(row, (list, tuple)):
def from_wkt(s):
"""
Parse a LineString geometry from a wkt string and return a new LineString object.
"""
if not _HAS_GEOMET:
raise DriverException("Geomet is required to deserialize a wkt geometry.")
try:
geom = wkt.loads(s)
except ValueError:
raise ValueError("Invalid WKT geometry: '{0}'".format(s))
if geom['type'] != 'LineString':
raise ValueError("Invalid WKT geometry type. Expected 'LineString', got '{0}': '{1}'".format(geom['type'], s))
geom['coordinates'] = list_contents_to_tuple(geom['coordinates'])
return LineString(coords=geom['coordinates'])
return geometry[:2]
def check_bounds(geometry):
if isinstance(geometry[0], (list, tuple)):
return list(map(check_bounds, geometry))
else:
if geometry[0] > 180 or geometry[0] < -180:
raise ValueError("Longitude is out of bounds, check your JSON format or data")
if geometry[1] > 90 or geometry[1] < -90:
raise ValueError("Latitude is out of bounds, check your JSON format or data")
# Discard z-coordinate, if it exists
geometry["coordinates"] = ensure_2d(geometry["coordinates"])
check_bounds(geometry["coordinates"])
wkt = geomet.wkt.dumps(geometry, decimals=decimals)
# Strip unnecessary spaces
wkt = re.sub(r"(?
g.add((spatial_ref, RDF.type, DCT.Location))
g.add((dataset_ref, DCT.spatial, spatial_ref))
if spatial_text:
g.add((spatial_ref, SKOS.prefLabel, Literal(spatial_text)))
if spatial_geom:
# GeoJSON
g.add((spatial_ref,
LOCN.geometry,
Literal(spatial_geom, datatype=GEOJSON_IMT)))
# WKT, because GeoDCAT-AP says so
try:
g.add((spatial_ref,
LOCN.geometry,
Literal(wkt.dumps(json.loads(spatial_geom),
decimals=4),
datatype=GSP.wktLiteral)))
except (TypeError, ValueError, InvalidGeoJSONException):
pass
# License
license_id = self._get_dataset_value(dataset_dict, 'license_id', default='')
license_url = self._get_dataset_value(dataset_dict, 'license_url', default='')
license_title = self._get_dataset_value(dataset_dict, 'license_title', default='')
license = None
if license_id or license_url or license_title:
if license_url and bool(urlparse.urlparse(license_url).netloc):
license = URIRef(license_url)
else:
id_string = dataset_ref.n3() + DCT.license.n3() + license_id + license_url + license_title
bnode_hash = hashlib.sha1(id_string.encode('utf-8'))
def from_wkt(s):
"""
Parse a Polygon geometry from a wkt string and return a new Polygon object.
"""
if not _HAS_GEOMET:
raise DriverException("Geomet is required to deserialize a wkt geometry.")
try:
geom = wkt.loads(s)
except ValueError:
raise ValueError("Invalid WKT geometry: '{0}'".format(s))
if geom['type'] != 'Polygon':
raise ValueError("Invalid WKT geometry type. Expected 'Polygon', got '{0}': '{1}'".format(geom['type'], s))
coords = geom['coordinates']
exterior = coords[0] if len(coords) > 0 else tuple()
interiors = coords[1:] if len(coords) > 1 else None
return Polygon(exterior=exterior, interiors=interiors)
g.add((spatial_ref, RDF.type, DCT.Location))
g.add((dataset_ref, DCT.spatial, spatial_ref))
if spatial_text:
g.add((spatial_ref, SKOS.prefLabel, Literal(spatial_text)))
if spatial_geom:
# GeoJSON
g.add((spatial_ref,
LOCN.geometry,
Literal(spatial_geom, datatype=GEOJSON_IMT)))
# WKT, because GeoDCAT-AP says so
try:
g.add((spatial_ref,
LOCN.geometry,
Literal(wkt.dumps(json.loads(spatial_geom),
decimals=4),
datatype=GSP.wktLiteral)))
except (TypeError, ValueError, InvalidGeoJSONException):
pass
# License
license_id = self._get_dataset_value(dataset_dict, 'license_id')
license_url = self._get_dataset_value(dataset_dict, 'license_url')
license_title = self._get_dataset_value(dataset_dict, 'license_title')
license = None
if license_id or license_url or license_title:
if license_url and bool(urlparse.urlparse(license_url).netloc):
license = URIRef(license_url)
else:
license = BNode()
# maybe a non-valid url
def _update(self):
"""updates the current row"""
txts = []
values = []
for k,v in self._values.items():
if k.lower() != "objectid" and \
k.lower() != 'shape':
txts.append("%s=?" % k)
values.append(v)
elif k.lower() == 'shape':
if isinstance(v, dict) and "coordinates" not in v:
v = self._header + dumps(v, False)
elif isinstance(v, dict) and "coordinates" in v:
v = self._gpheader + geometwkb.dumps(obj=v)
elif isinstance(v, str):
gj = geometwkt.loads(v)
v = self._gpheader + geometwkb.dumps(obj=gj)
elif isinstance(v, (bytes, bytearray)):
if isinstance(v, (bytearray)):
v = bytes(v)
if len(v) > 2 and \
v[:2] != b'GB':
v = self._gpheader + v
elif v is None:
v = self._gpheader + b'0x000000000000f87f'
else:
raise ValueError(("Shape column must be Esri JSON dictionary, "
"WKT, GeoJSON dictionary, or WKB (bytes)"))
txts.append("%s=?" % k)
values.append(v)