Source code for registrar.utils

"""
utils.py
=========

Contains helper functions

"""


from datetime import datetime
import importlib


[docs]def isoformat(dt: datetime) -> str: """Formats a datetime object to an ISO string. Timezone naive datetimes are are treated as UTC Zulu. UTC Zulu is expressed with the proper "Z" ending and not with the "+00:00" offset declaration. Args: dt (datetime): datetime to encode Returns: str: iso formatted datetime """ if not dt.utcoffset(): dt = dt.replace(tzinfo=None) return dt.isoformat("T") + "Z" return dt.isoformat("T")
[docs]def import_by_path(path: str): """Imports the object from the referenced module. Args: path (str): the dotted Python path, where the last element is the object in the referenced module. """ module_path, _, object_name = path.rpartition(".") return getattr(importlib.import_module(module_path), object_name)
[docs]def extract_footprint(env: dict, vsipath: str) -> str: """Extracts the footprint from the extent of file. This method is currently imprecise due to the extent being different from the actual footprint in cases of nodata, unless the geotiff has geometry stored as geojson in a metadata attribute `geometry` Args: env (dict): environment vars for gdal vsipath (str): vsi path to file Returns: str: WKT formatted footprint """ from osgeo.osr import SpatialReference, CoordinateTransformation from django.contrib.gis.geos import Polygon, GEOSGeometry from eoxserver.contrib.gdal import open_with_env, get_extent f = open_with_env(vsipath, env) try: geojson_footprint = f.GetMetadata()["geometry"] footprint = GEOSGeometry(geojson_footprint) except KeyError: extent = get_extent(f) dscrs = f.GetProjection() dcrs = SpatialReference() dcrs.ImportFromWkt(dscrs) wgs84 = SpatialReference() wgs84.ImportFromEPSG(4326) dcrs2wgs84 = CoordinateTransformation(dcrs, wgs84) ll = dcrs2wgs84.TransformPoint(extent[0], extent[1]) ur = dcrs2wgs84.TransformPoint(extent[2], extent[3]) footprint = Polygon( ( (ll[1], ll[0]), (ur[1], ll[0]), (ur[1], ur[0]), (ll[1], ur[0]), (ll[1], ll[0]), ) ) return footprint.wkt
[docs]def extract_metadata(env: dict, vsipath: str) -> dict: """Extracts metadata from file Args: env (dict): environment vars for vsipath (str): vsi path to file Returns: dict: metadata as key value pairs """ from eoxserver.contrib.gdal import open_with_env f = open_with_env(vsipath, env) return f.GetMetadata()