Skip to content

Commit

Permalink
fix to logic determining if context.matched in response
Browse files Browse the repository at this point in the history
  • Loading branch information
dchandan committed Feb 27, 2024
1 parent 53c0731 commit 83c5e8d
Showing 1 changed file with 15 additions and 47 deletions.
62 changes: 15 additions & 47 deletions pystac_client/item_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,13 @@ def __geo_interface__(self) -> Dict[str, Any]:

def __getattr__(name: str) -> Any:
if name in ("DEFAUL_LIMIT", "DEFAULT_LIMIT_AND_MAX_ITEMS"):
warnings.warn(
f"{name} is deprecated and will be removed in v0.8", DeprecationWarning
)
warnings.warn(f"{name} is deprecated and will be removed in v0.8", DeprecationWarning)
return 100
raise AttributeError(f"module {__name__} has no attribute {name}")


# from https://gist.github.com/angstwad/bf22d1822c38a92ec0a9#gistcomment-2622319
def dict_merge(
dct: Dict[Any, Any], merge_dct: Dict[Any, Any], add_keys: bool = True
) -> Dict[Any, Any]:
def dict_merge(dct: Dict[Any, Any], merge_dct: Dict[Any, Any], add_keys: bool = True) -> Dict[Any, Any]:
"""Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of
Expand Down Expand Up @@ -308,9 +304,7 @@ def __init__(
"fields": self._format_fields(fields),
}

self._parameters: Dict[str, Any] = {
k: v for k, v in params.items() if v is not None
}
self._parameters: Dict[str, Any] = {k: v for k, v in params.items() if v is not None}

def get_parameters(self) -> Dict[str, Any]:
if self.method == "POST":
Expand All @@ -329,9 +323,7 @@ def _clean_params_for_get_request(self) -> Dict[str, Any]:
if "collections" in params:
params["collections"] = ",".join(params["collections"])
if "intersects" in params:
params["intersects"] = json.dumps(
params["intersects"], separators=(",", ":")
)
params["intersects"] = json.dumps(params["intersects"], separators=(",", ":"))
if "query" in params:
params["query"] = json.dumps(params["query"], separators=(",", ":"))
if "sortby" in params:
Expand Down Expand Up @@ -399,9 +391,7 @@ def _format_query(self, value: Optional[QueryLike]) -> Optional[Dict[str, Any]]:
return query

@staticmethod
def _format_filter_lang(
_filter: Optional[FilterLike], value: Optional[FilterLangLike]
) -> Optional[str]:
def _format_filter_lang(_filter: Optional[FilterLike], value: Optional[FilterLangLike]) -> Optional[str]:
if _filter is None:
return None

Expand Down Expand Up @@ -527,10 +517,7 @@ def _format_datetime(self, value: Optional[DatetimeLike]) -> Optional[Datetime]:
backup_end, end = self._to_isoformat_range(components[1])
return f"{start}/{end or backup_end}"
else:
raise Exception(
"too many datetime components "
f"(max=2, actual={len(components)}): {value}"
)
raise Exception("too many datetime components " f"(max=2, actual={len(components)}): {value}")

@staticmethod
def _format_collections(value: Optional[CollectionsLike]) -> Optional[Collections]:
Expand Down Expand Up @@ -582,9 +569,7 @@ def _format_sortby(self, value: Optional[SortbyLike]) -> Optional[Sortby]:
elif value and isinstance(value[0], dict):
return value # type: ignore

raise Exception(
"sortby must be of type None, str, List[str], or List[Dict[str, str]"
)
raise Exception("sortby must be of type None, str, List[str], or List[Dict[str, str]")

@staticmethod
def _sortby_part_to_dict(part: str) -> Dict[str, str]:
Expand All @@ -597,12 +582,7 @@ def _sortby_part_to_dict(part: str) -> Dict[str, str]:

@staticmethod
def _sortby_dict_to_str(sortby: Sortby) -> str:
return ",".join(
[
f"{'+' if sort['direction'] == 'asc' else '-'}{sort['field']}"
for sort in sortby
]
)
return ",".join([f"{'+' if sort['direction'] == 'asc' else '-'}{sort['field']}" for sort in sortby])

def _format_fields(self, value: Optional[FieldsLike]) -> Optional[Fields]:
if value is None:
Expand All @@ -618,9 +598,7 @@ def _format_fields(self, value: Optional[FieldsLike]) -> Optional[Fields]:
if isinstance(value, dict):
return value

raise Exception(
"sortby must be of type None, str, List[str], or List[Dict[str, str]"
)
raise Exception("sortby must be of type None, str, List[str], or List[Dict[str, str]")

@staticmethod
def _fields_to_dict(fields: List[str]) -> Fields:
Expand Down Expand Up @@ -651,10 +629,7 @@ def _format_intersects(value: Optional[IntersectsLike]) -> Optional[Intersects]:
return dict(json.loads(value))
if hasattr(value, "__geo_interface__"):
return dict(deepcopy(getattr(value, "__geo_interface__")))
raise Exception(
"intersects must be of type None, str, dict, or an object that "
"implements __geo_interface__"
)
raise Exception("intersects must be of type None, str, dict, or an object that " "implements __geo_interface__")

@lru_cache(1)
def matched(self) -> Optional[int]:
Expand All @@ -671,7 +646,7 @@ def matched(self) -> Optional[int]:
resp = self._stac_io.read_json(self.url, method=self.method, parameters=params)
found = None
if "context" in resp:
found = resp["context"]["matched"]
found = resp["context"].get("matched", None)
elif "numberMatched" in resp:
found = resp["numberMatched"]
if found is None:
Expand Down Expand Up @@ -718,9 +693,7 @@ def pages(self) -> Iterator[ItemCollection]:
if isinstance(self._stac_io, StacApiIO):
for page in self.pages_as_dicts():
# already signed in pages_as_dicts
yield ItemCollection.from_dict(
page, preserve_dict=False, root=self.client
)
yield ItemCollection.from_dict(page, preserve_dict=False, root=self.client)

def pages_as_dicts(self) -> Iterator[Dict[str, Any]]:
"""Iterator that yields :class:`dict` instances for each page
Expand All @@ -732,9 +705,7 @@ def pages_as_dicts(self) -> Iterator[Dict[str, Any]]:
"""
if isinstance(self._stac_io, StacApiIO):
num_items = 0
for page in self._stac_io.get_pages(
self.url, self.method, self.get_parameters()
):
for page in self._stac_io.get_pages(self.url, self.method, self.get_parameters()):
call_modifier(self.modifier, page)
features = page.get("features", [])
if features:
Expand Down Expand Up @@ -763,9 +734,7 @@ def item_collection(self) -> ItemCollection:
# without mutating what's in the cache.
feature_collection = self.item_collection_as_dict.__wrapped__(self)
# already signed in item_collection_as_dict
return ItemCollection.from_dict(
feature_collection, preserve_dict=False, root=self.client
)
return ItemCollection.from_dict(feature_collection, preserve_dict=False, root=self.client)

@lru_cache(1)
def item_collection_as_dict(self) -> Dict[str, Any]:
Expand Down Expand Up @@ -862,8 +831,7 @@ def get_all_items_as_dict(self) -> Dict[str, Any]:
Dict : A GeoJSON FeatureCollection
"""
warnings.warn(
"get_all_items_as_dict() is deprecated, use item_collection_as_dict() "
"instead.",
"get_all_items_as_dict() is deprecated, use item_collection_as_dict() " "instead.",
FutureWarning,
)
return self.item_collection_as_dict()

0 comments on commit 83c5e8d

Please sign in to comment.