Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jul 22, 2024
1 parent a12eb2c commit 985897f
Show file tree
Hide file tree
Showing 14 changed files with 534 additions and 534 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ repos:
args: [--fix]
# Run the formatter.
- id: ruff-format
args: ["--config", "format.quote-style = 'single'"]
args: ['--config', "format.quote-style = 'single'"]
2 changes: 1 addition & 1 deletion pygeoapi_plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@
#
# =================================================================

__version__ = "0.1.0"
__version__ = '0.1.0'
28 changes: 14 additions & 14 deletions pygeoapi_plugins/formatter/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ def __init__(self, formatter_def: dict):
"""

geom = False
self.uri_field = formatter_def.get("uri_field")
super().__init__({"name": "xml", "geom": geom})
self.mimetype = "application/xml; charset=utf-8"
self.uri_field = formatter_def.get('uri_field')
super().__init__({'name': 'xml', 'geom': geom})
self.mimetype = 'application/xml; charset=utf-8'

def write(self, options: dict = {}, data: dict = None) -> str:
"""
Expand All @@ -76,40 +76,40 @@ def write(self, options: dict = {}, data: dict = None) -> str:
"""

try:
feature = list(data["features"][0])
feature = list(data['features'][0])
except IndexError:
LOGGER.error("no features")
LOGGER.error('no features')
return str()

lastmod = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
lastmod = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
root = ET.fromstring(URLSET)
tree = ET.ElementTree(root)
try:
ET.indent(tree)
except AttributeError:
LOGGER.warning("Unable to indent")
LOGGER.warning('Unable to indent')

try:
for i, feature in enumerate(data["features"]):
for i, feature in enumerate(data['features']):
if i >= 50000:
LOGGER.warning("Maximum size of sitemap reached")
LOGGER.warning('Maximum size of sitemap reached')
break

try:
loc = feature["properties"][self.uri_field]
loc = feature['properties'][self.uri_field]
except KeyError:
loc = feature["@id"]
loc = feature['@id']

_ = URLSET_FOREACH.format(loc, lastmod)
root.append(ET.fromstring(_))

except ValueError as err:
LOGGER.error(err)
raise FormatterSerializationError("Error writing XML output")
raise FormatterSerializationError('Error writing XML output')

output = io.BytesIO()
tree.write(output, encoding="utf-8", xml_declaration=True)
tree.write(output, encoding='utf-8', xml_declaration=True)
return output.getvalue()

def __repr__(self):
return f"<XMLFormatter> {self.name}"
return f'<XMLFormatter> {self.name}'
156 changes: 78 additions & 78 deletions pygeoapi_plugins/process/intersect.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,77 +40,77 @@

LOGGER = logging.getLogger(__name__)

with open(os.getenv("PYGEOAPI_CONFIG"), encoding="utf8") as fh:
with open(os.getenv('PYGEOAPI_CONFIG'), encoding='utf8') as fh:
CONFIG = yaml_load(fh)
COLLECTIONS = filter_dict_by_key_value(CONFIG["resources"], "type", "collection")
COLLECTIONS = filter_dict_by_key_value(CONFIG['resources'], 'type', 'collection')
# TODO: Filter collections for those that support CQL


PROCESS_DEF = CONFIG["resources"]["intersector"]
PROCESS_DEF = CONFIG['resources']['intersector']
PROCESS_DEF.update(
{
"version": "0.1.0",
"id": "intersector",
"title": "Intersector",
"description": (
"A process that takes a URL of a geoJSON, " "and returns all intersections."
'version': '0.1.0',
'id': 'intersector',
'title': 'Intersector',
'description': (
'A process that takes a URL of a geoJSON, ' 'and returns all intersections.'
),
"links": [
'links': [
{
"type": "text/html",
"rel": "about",
"title": "information",
"href": "https://example.org/process",
"hreflang": "en-US",
'type': 'text/html',
'rel': 'about',
'title': 'information',
'href': 'https://example.org/process',
'hreflang': 'en-US',
}
],
"inputs": {
"url": {
"title": {"en": "Feature URL"},
"description": {"en": "URL of valid feature geoJSON"},
"keywords": {"en": ["geojson", "feature", "url"]},
"schema": {"type": "string", "default": None},
"minOccurs": 1,
"maxOccurs": 1,
"metadata": None, # TODO how to use?
'inputs': {
'url': {
'title': {'en': 'Feature URL'},
'description': {'en': 'URL of valid feature geoJSON'},
'keywords': {'en': ['geojson', 'feature', 'url']},
'schema': {'type': 'string', 'default': None},
'minOccurs': 1,
'maxOccurs': 1,
'metadata': None, # TODO how to use?
},
"collection": {
"title": {"en": "Feature Collection"},
"description": {"en": "Feature Collection"},
"keywords": {"en": ["OGC API", "collection"]},
"schema": {
"type": "string",
"example": next(iter(COLLECTIONS)),
"enum": list(COLLECTIONS),
'collection': {
'title': {'en': 'Feature Collection'},
'description': {'en': 'Feature Collection'},
'keywords': {'en': ['OGC API', 'collection']},
'schema': {
'type': 'string',
'example': next(iter(COLLECTIONS)),
'enum': list(COLLECTIONS),
},
"minOccurs": 1,
"maxOccurs": 1,
"metadata": None, # TODO how to use?
'minOccurs': 1,
'maxOccurs': 1,
'metadata': None, # TODO how to use?
},
"geom_field": {
"title": {"en": "Geometry Field"},
"description": {"en": "Geometry field of valid feature intersect"},
"keywords": {"en": ["geometry", "intersect", "field"]},
"schema": {"type": "string", "default": "geom"},
"minOccurs": 0,
"maxOccurs": 1,
"metadata": None, # TODO how to use?
'geom_field': {
'title': {'en': 'Geometry Field'},
'description': {'en': 'Geometry field of valid feature intersect'},
'keywords': {'en': ['geometry', 'intersect', 'field']},
'schema': {'type': 'string', 'default': 'geom'},
'minOccurs': 0,
'maxOccurs': 1,
'metadata': None, # TODO how to use?
},
},
"outputs": {
"path": {
"title": {"en": "FeatureCollection"},
"description": {
"en": "A geoJSON FeatureCollection of the "
"path generated by the intersection process"
'outputs': {
'path': {
'title': {'en': 'FeatureCollection'},
'description': {
'en': 'A geoJSON FeatureCollection of the '
'path generated by the intersection process'
},
"schema": {"type": "object", "contentMediaType": "application/json"},
'schema': {'type': 'object', 'contentMediaType': 'application/json'},
}
},
"example": {
"inputs": {
"url": "https://demo.pygeoapi.io/master/collections/obs/items/238",
"collection": next(iter(COLLECTIONS)),
'example': {
'inputs': {
'url': 'https://demo.pygeoapi.io/master/collections/obs/items/238',
'collection': next(iter(COLLECTIONS)),
}
},
}
Expand All @@ -128,7 +128,7 @@ def __init__(self, processor_def):
:returns: pygeoapi.process.intersect.IntersectionProcessor
"""
LOGGER.debug("IntersectionProcesser init")
LOGGER.debug('IntersectionProcesser init')
super().__init__(processor_def, PROCESS_DEF)

def execute(self, data):
Expand All @@ -139,39 +139,39 @@ def execute(self, data):
:returns: 'application/json'
"""
mimetype = "application/json"
mimetype = 'application/json'

if not data.get("url") or not data.get("collection"):
raise ProcessorExecuteError(f"Invalid input: {data.items()}")
feature_url = data["url"]
geom_field = data.get("geom_field")
collection = data["collection"]
if not data.get('url') or not data.get('collection'):
raise ProcessorExecuteError(f'Invalid input: {data.items()}')
feature_url = data['url']
geom_field = data.get('geom_field')
collection = data['collection']

LOGGER.debug(f"Fetching {feature_url}")
params = {"f": "json"}
LOGGER.debug(f'Fetching {feature_url}')
params = {'f': 'json'}
feature = get(feature_url, params=params).json()
if not feature.get("geometry"):
raise ProcessorExecuteError(f"Invalid geoJSON: {feature.items()}")
if not feature.get('geometry'):
raise ProcessorExecuteError(f'Invalid geoJSON: {feature.items()}')

for cname, c in COLLECTIONS.items():
if str(collection) != cname:
continue

p = get_provider_default(c["providers"])
provider = load_plugin("provider", p)
if "geom_field" in p:
geom_field = p["geom_field"]
LOGGER.debug(f"Using geom from configuration: {geom_field}")
p = get_provider_default(c['providers'])
provider = load_plugin('provider', p)
if 'geom_field' in p:
geom_field = p['geom_field']
LOGGER.debug(f'Using geom from configuration: {geom_field}')
else:
LOGGER.debug(f"Using provided geom field: {geom_field}")
LOGGER.debug(f'Using provided geom field: {geom_field}')
if not geom_field:
msg = f"Invalid geom_field: {data.items()}"
msg = f'Invalid geom_field: {data.items()}'
raise ProcessorExecuteError(msg)

LOGGER.debug(f"Intesecting {cname} with backend {provider}")
LOGGER.debug(f'Intesecting {cname} with backend {provider}')
outputs = self._intersect(feature, geom_field, provider)

LOGGER.debug("Returning response")
LOGGER.debug('Returning response')
return mimetype, outputs

def _intersect(self, feature, geom_field, provider):
Expand All @@ -185,14 +185,14 @@ def _intersect(self, feature, geom_field, provider):
:returns: List of GeoJSON Features
"""
filter_ = parse_cql_json(
{"intersects": [{"property": geom_field}, feature["geometry"]]}
{'intersects': [{'property': geom_field}, feature['geometry']]}
)
LOGGER.debug(f"Making CQL query: {filter_}")
_ = provider.query(resulttype="hits", filterq=filter_)
fc = provider.query(limit=_["numberMatched"], filterq=filter_)
LOGGER.debug(f'Making CQL query: {filter_}')
_ = provider.query(resulttype='hits', filterq=filter_)
fc = provider.query(limit=_['numberMatched'], filterq=filter_)

LOGGER.info(f'Returning {fc["numberReturned"]} intersections')
return fc

def __repr__(self):
return f"<IntersectionProcessor> {self.name}"
return f'<IntersectionProcessor> {self.name}'
Loading

0 comments on commit 985897f

Please sign in to comment.