Source code for pygeoapi.provider.base

# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2022 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import json
import logging
from enum import Enum

LOGGER = logging.getLogger(__name__)


[docs]class SchemaType(Enum): item = 'item' create = 'create' update = 'update' replace = 'replace'
[docs]class BaseProvider: """generic Provider ABC"""
[docs] def __init__(self, provider_def): """ Initialize object :param provider_def: provider definition :returns: pygeoapi.provider.base.BaseProvider """ try: self.name = provider_def['name'] self.type = provider_def['type'] self.data = provider_def['data'] except KeyError: raise RuntimeError('name/type/data are required') self.editable = provider_def.get('editable', False) self.options = provider_def.get('options', None) self.id_field = provider_def.get('id_field', None) self.uri_field = provider_def.get('uri_field', None) self.x_field = provider_def.get('x_field', None) self.y_field = provider_def.get('y_field', None) self.time_field = provider_def.get('time_field') self.title_field = provider_def.get('title_field') self.properties = provider_def.get('properties', []) self.file_types = provider_def.get('file_types', []) self.fields = {} self.filename = None # for coverage providers self.axes = [] self.crs = None self.num_bands = None
[docs] def get_fields(self): """ Get provider field information (names, types) :returns: dict of fields """ raise NotImplementedError()
[docs] def get_schema(self, schema_type: SchemaType = SchemaType.item): """ Get provider schema model :param schema_type: `SchemaType` of schema (default is 'item') :returns: tuple pair of `str` of media type and `dict` of schema (i.e. JSON Schema) """ raise NotImplementedError()
[docs] def get_data_path(self, baseurl, urlpath, dirpath): """ Gets directory listing or file description or raw file dump :param baseurl: base URL of endpoint :param urlpath: base path of URL :param dirpath: directory basepath (equivalent of URL) :returns: `dict` of file listing or `dict` of GeoJSON item or raw file """ raise NotImplementedError()
[docs] def get_metadata(self): """ Provide data/file metadata :returns: `dict` of metadata construct (format determined by provider/standard) """ raise NotImplementedError()
[docs] def query(self): """ query the provider :returns: dict of 0..n GeoJSON features or coverage data """ raise NotImplementedError()
[docs] def get(self, identifier): """ query the provider by id :param identifier: feature id :returns: dict of single GeoJSON feature """ raise NotImplementedError()
[docs] def create(self, item): """ Create a new item :param item: `dict` of new item :returns: identifier of created item """ raise NotImplementedError()
[docs] def update(self, identifier, item): """ Updates an existing item :param identifier: feature id :param item: `dict` of partial or full item :returns: `bool` of update result """ raise NotImplementedError()
[docs] def delete(self, identifier): """ Deletes an existing item :param identifier: item id :returns: `bool` of deletion result """ raise NotImplementedError()
[docs] def get_coverage_domainset(self): """ Provide coverage domainset :returns: CIS JSON object of domainset metadata """ raise NotImplementedError()
[docs] def get_coverage_rangetype(self): """ Provide coverage rangetype :returns: CIS JSON object of rangetype metadata """ raise NotImplementedError()
[docs] def _load_and_prepare_item(self, item, identifier=None, raise_if_exists=True): """ Helper function to load a record, detect its idenfier and prepare a record item :param item: `str` of incoming item data :param identifier: `str` of item identifier (optional) :param raise_if_exists: `bool` of whether to check if record already exists :returns: `tuple` of item identifier and item data/payload """ identifier2 = None msg = None LOGGER.debug('Loading data') LOGGER.debug('Data: {}'.format(item)) try: json_data = json.loads(item) except TypeError as err: LOGGER.error(err) msg = 'Invalid data' except json.decoder.JSONDecodeError as err: LOGGER.error(err) msg = 'Invalid JSON data' if msg is not None: raise ProviderInvalidDataError(msg) LOGGER.debug('Detecting identifier') if identifier is not None: identifier2 = identifier else: try: identifier2 = json_data['id'] except KeyError: LOGGER.debug('Cannot find id; trying properties.identifier') try: identifier2 = json_data['properties']['identifier'] except KeyError: LOGGER.debug('Cannot find properties.identifier') if identifier2 is None: msg = 'Missing identifier (id or properties.identifier)' LOGGER.error(msg) raise ProviderInvalidDataError(msg) if 'geometry' not in json_data or 'properties' not in json_data: msg = 'Missing core GeoJSON geometry or properties' LOGGER.error(msg) raise ProviderInvalidDataError(msg) if raise_if_exists: LOGGER.debug('Querying database whether item exists') try: _ = self.get(identifier2) msg = 'record already exists' LOGGER.error(msg) raise ProviderInvalidDataError(msg) except ProviderItemNotFoundError: LOGGER.debug('record does not exist') return identifier2, json_data
[docs] def __repr__(self): return '<BaseProvider> {}'.format(self.type)
[docs]class ProviderGenericError(Exception): """provider generic error""" pass
[docs]class ProviderConnectionError(ProviderGenericError): """provider connection error""" pass
[docs]class ProviderTypeError(ProviderGenericError): """provider type error""" pass
[docs]class ProviderInvalidQueryError(ProviderGenericError): """provider invalid query error""" pass
[docs]class ProviderQueryError(ProviderGenericError): """provider query error""" pass
[docs]class ProviderItemNotFoundError(ProviderGenericError): """provider item not found query error""" pass
[docs]class ProviderNoDataError(ProviderGenericError): """provider no data error""" pass
[docs]class ProviderNotFoundError(ProviderGenericError): """provider not found error""" pass
[docs]class ProviderVersionError(ProviderGenericError): """provider incorrect version error""" pass
[docs]class ProviderInvalidDataError(ProviderGenericError): """provider invalid data error""" pass