Skip to content

Commit

Permalink
Cleanup and add FeatureType
Browse files Browse the repository at this point in the history
  • Loading branch information
danduk82 committed Oct 14, 2024
1 parent ff88ecf commit 1567db6
Show file tree
Hide file tree
Showing 24 changed files with 607 additions and 153 deletions.
26 changes: 26 additions & 0 deletions geoservercloud/geoservercloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from geoservercloud import utils
from geoservercloud.models import (
DataStores,
FeatureType,
FeatureTypes,
KeyDollarListDict,
PostGisDataStore,
Style,
Expand Down Expand Up @@ -304,6 +306,30 @@ def create_wmts_store(
self.rest_endpoints.wmtsstore(workspace_name, name), json=payload
)

def get_feature_types(
self, workspace_name: str, datastore_name: str
) -> dict[str, Any]:
"""
Get all feature types for a given workspace and datastore
"""
featuretypes = FeatureTypes.from_response(
self.get_request(
self.rest_endpoints.featuretypes(workspace_name, datastore_name)
)
)
return featuretypes

def get_feature_type(
self, workspace_name: str, datastore_name: str, feature_type_name: str
) -> dict[str, Any]:
return FeatureType.from_response(
self.get_request(
self.rest_endpoints.featuretype(
workspace_name, datastore_name, feature_type_name
)
)
)

def create_feature_type(
self,
layer: str,
Expand Down
11 changes: 8 additions & 3 deletions geoservercloud/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from .common import KeyDollarListDict
from .dataStore import PostGisDataStore
from .dataStores import DataStores
from .common import I18N, KeyDollarListDict
from .datastore import PostGisDataStore
from .datastores import DataStores
from .featuretype import FeatureType
from .featuretypes import FeatureTypes
from .style import Style
from .styles import Styles
from .workspace import Workspace
Expand All @@ -9,6 +11,9 @@
__all__ = [
"DataStores",
"KeyDollarListDict",
"FeatureType",
"FeatureTypes",
"I18N",
"PostGisDataStore",
"Style",
"Styles",
Expand Down
50 changes: 48 additions & 2 deletions geoservercloud/models/common.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import json
import logging
from typing import Any

log = logging.getLogger()


class KeyDollarListDict(dict):
def __init__(self, input_list=None, input_dict=None, *args, **kwargs):
def __init__(
self,
input_list: list | None = None,
input_dict: dict | None = None,
*args,
**kwargs
):
super().__init__(*args, **kwargs)
self.key_prefix = "@key"
self.value_prefix = "$"
Expand All @@ -15,7 +22,7 @@ def __init__(self, input_list=None, input_dict=None, *args, **kwargs):
self.update(input_dict)
log.debug(self)

def deserialize(self, input_list):
def deserialize(self, input_list: list):
for item in input_list:
key = item[self.key_prefix]
if self.value_prefix in item:
Expand All @@ -39,3 +46,42 @@ def __str__(self):
def update(self, other: dict): # type: ignore
for key, value in other.items():
super().__setitem__(key, value)


class I18N:
"""
Class to handle internationalization of strings
items like title, abstract, etc. that can be internationalized
become a dictionary with the key being the language code
and their key in the payload changes to internationalizedTitle, internationalizedAbstract, etc.
"""

def __init__(self, keys: tuple[str, Any], value: str | dict) -> None:
self._str_key = keys[0]
self._i18n_key = keys[1]
self._value = value
if isinstance(value, str):
self._payload = (self.str_key, self._value)
elif isinstance(value, dict):
self._payload = (self._i18n_key, self._value) # type: ignore
else:
raise ValueError("Invalid value type")

@property
def str_key(self):
return self._str_key

@property
def i18n_key(self):
return self._i18n_key

@property
def value(self):
return self._value

@property
def payload_tuple(self):
return self._payload

def __repr__(self):
return json.dumps({self._payload[0]: self._payload[1]}, indent=4)
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import json
import logging

from requests.models import Response

from . import KeyDollarListDict

log = logging.getLogger()
Expand Down Expand Up @@ -49,7 +51,7 @@ def put_payload(self):
return payload

@classmethod
def from_response(cls, response):
def from_response(cls, response: Response):
if response.status_code == 404:
return None
json_data = response.json()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging

from requests.models import Response

log = logging.getLogger()


Expand All @@ -14,7 +16,7 @@ def datastores(self):
return self._datastores

@classmethod
def from_response(cls, response):
def from_response(cls, response: Response):
json_data = response.json()
datastores = []
workspace_name = (
Expand Down
134 changes: 134 additions & 0 deletions geoservercloud/models/featuretype.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import json

from requests.models import Response

from geoservercloud.models import I18N


# TODO: import more default values from Templates
class FeatureType:
def __init__(
self,
namespace_name: str,
name: str,
native_name: str,
srs: str = "EPSG:4326",
title: str | dict = "New Layer",
abstract: str | dict = "New Layer",
keywords={},
metadata_url=None,
metadata_type="TC211",
metadata_format="text/xml",
attributes: dict | None = None,
) -> None:
self._namespace_name = namespace_name
self._name = name
self._title = I18N(("title", "internationalTitle"), title)
self._abstract = I18N(("abstract", "internationalAbstract"), abstract)
self._native_name = native_name
self._srs = srs
self._keywords = keywords
self._attributes = attributes
self.create_metadata_link(metadata_url, metadata_type, metadata_format)

@property
def namespace_name(self):
return self._namespace_name

@property
def name(self):
return self._name

@property
def title(self):
return self._title

@property
def abstract(self):
return self._abstract

@property
def native_name(self):
return self._native_name

@property
def srs(self):
return self._srs

@property
def keywords(self):
return self._keywords

@property
def metadataLink(self):
return self._metadataLink

@property
def attributes(self):
return self._attributes

def post_payload(self):
payload = {
"featureType": {
"name": self.name,
"nativeName": self.native_name,
self._title.payload_tuple[0]: self._title.payload_tuple[1],
self._abstract.payload_tuple[0]: self._abstract.payload_tuple[1],
"srs": self.srs,
"keywords": self.keywords,
}
}
if self.metadataLink != {}:
payload["featureType"]["metadataLinks"] = self.metadataLink
if self.attributes:
payload["featureType"]["attributes"] = self.attributes
return payload

def create_metadata_link(
self, metadata_url=None, metadata_type="TC211", metadata_format="text/xml"
):
self._metadataLink = {}
if metadata_url:
self._metadataLink["metadataLink"] = {
"type": metadata_format,
"metadataType": metadata_type,
"content": metadata_url,
}

@classmethod
def from_response(cls, response: Response):
json_data = response.json()
try:
abstract = json_data["featureType"]["abstract"]
except KeyError:
abstract = json_data["featureType"]["internationalAbstract"]
try:
title = json_data["featureType"]["title"]
except KeyError:
title = json_data["featureType"]["internationalTitle"]

return cls(
namespace_name=json_data["featureType"]["namespace"]["name"],
name=json_data["featureType"]["name"],
native_name=json_data["featureType"]["nativeName"],
title=title,
abstract=abstract,
srs=json_data["featureType"]["srs"],
keywords=json_data["featureType"]["keywords"],
attributes=json_data["featureType"].get("attributes", None),
metadata_url=json_data["featureType"]
.get("metadataLinks", {})
.get("metadataLink", {})
.get("content"),
metadata_type=json_data["featureType"]
.get("metadataLinks", {})
.get("metadataLink", {})
.get("metadataType"),
metadata_format=json_data["featureType"]
.get("metadataLinks", {})
.get("metadataLink", {})
.get("type"),
)

def __repr__(self):
return json.dumps(self.post_payload(), indent=4)
22 changes: 22 additions & 0 deletions geoservercloud/models/featuretypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import json
from requests.models import Response

class FeatureTypes:

def __init__(self, featuretypes: list = []) -> None:
self._featuretypes = featuretypes

@property
def featuretypes(self):
return self._featuretypes

@classmethod
def from_response(cls, response: Response):
featuretypes = []
json_data = response.json()
for featuretype in json_data.get('featureTypes', {}).get('featureType', []):
featuretypes.append(featuretype['name'])
return cls(featuretypes)

def __repr__(self):
return json.dumps(self._featuretypes, indent=4)
32 changes: 21 additions & 11 deletions geoservercloud/models/style.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json

import xmltodict
from requests.models import Response


class Style:
Expand All @@ -16,8 +17,8 @@ def __init__(
date_modified: str | None = None,
legend_url: str | None = None,
legend_format: str | None = None,
legend_width: str | None = None,
legend_height: str | None = None,
legend_width: int | None = None,
legend_height: int | None = None,
) -> None:
self._workspace = workspace
self._name = name
Expand All @@ -26,7 +27,9 @@ def __init__(
self._filename = filename
self._date_created = date_created
self._date_modified = date_modified
self.create_legend(legend_url, legend_format, legend_width, legend_height)
self._legend = self.create_legend(
legend_url, legend_format, legend_width, legend_height
)

# create one property for each attribute
@property
Expand Down Expand Up @@ -61,19 +64,26 @@ def date_modified(self):
def legend(self):
return self._legend

def create_legend(self, url, image_format, width, height):
def create_legend(
self,
url: str | None,
image_format: str | None,
width: int | None,
height: int | None,
):
if any([url, image_format, width, height]):
self._legend = {}
legend: dict = {}
if url:
self.legend["onlineResource"] = url
legend["onlineResource"] = url
if image_format:
self.legend["format"] = image_format
legend["format"] = image_format
if width:
self.legend["width"] = width
legend["width"] = width
if height:
self.legend["height"] = height
legend["height"] = height
else:
self._legend = None
legend = None # type: ignore
return legend

def put_payload(self):
payload = {
Expand All @@ -92,7 +102,7 @@ def post_payload(self):
return self.put_payload()

@classmethod
def from_response(cls, response):
def from_response(cls, response: Response):
json_data = response.json()
style_data = json_data.get("style", {})
return cls(
Expand Down
Loading

0 comments on commit 1567db6

Please sign in to comment.