Skip to content
Snippets Groups Projects
spatial.py 1.85 KiB
Newer Older
  • Learn to ignore specific revisions
  • # encoding: utf-8
    
    from ckan.common import config
    
    Dennis's avatar
    Dennis committed
    import json
    
    import urllib2
    
    log = __import__('logging').getLogger(__name__)
    
    
    class Spatial(object):
        def __init__(self, uri, text):
            self.uri = uri
            self.text = text
    
    
    class SpatialRegister(object):
        def __init__(self):
            spatial_url = config.get('ckanext.odsh.spatial.mapping', None)
            if spatial_url:
                self.load_spatial(spatial_url)
            else:
                default_spatial_dict = dict()
                self._create_spatial_list(default_spatial_dict)
    
        def load_spatial(self, spatial_url):
            try:
                response = urllib2.urlopen(spatial_url)
                response_body = response.read()
            except Exception as inst:
                msg = "Couldn't connect to spatial service %r: %s" % (spatial_url, inst)
                raise Exception(msg)
            try:
                spatial_data = json.loads(response_body)
            except Exception as inst:
                msg = "Couldn't read response from spatial service %r: %s" % (response_body, inst)
    
    Dennis's avatar
    Dennis committed
                raise Exception(msg)
    
            self._create_spatial_list(spatial_data, spatial_url)
    
        def _create_spatial_list(self, spatial_data, spatial_url=''):
            if isinstance(spatial_data, dict):
                self.spatials = list()
                for entity in spatial_data:
                    self.spatials.append(Spatial(entity, spatial_data[entity]['spatial_text']))
            else:
                msg = "Spatials at %s must be dictionary(json)" % spatial_url
                raise ValueError(msg)
    
        def __getitem__(self, key, default=Exception):
            for spatial in self.spatials:
                if key == spatial.uri:
                    return spatial
                if default != Exception:
                    return default
                else:
                    raise KeyError("Spatial not found: %s" % key)
    
        def values(self):
            return self.spatials