Skip to content

Commit 0a4ba64

Browse files
committed
Version 0.5 - add datastore creation and tests. Small update of API: update_from_yaml instead of update_yaml
1 parent 84829f8 commit 0a4ba64

15 files changed

Lines changed: 683 additions & 344 deletions

.idea/workspace.xml

Lines changed: 280 additions & 292 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ The first task is to create an API key file. By default this is assumed to be ca
4545

4646
To include the HDX Python library in your project, pip install the line below or add the following to your `requirements.txt` file:
4747

48-
git+git://github.com/ocha-dap/hdx-python-api.git@v0.42#egg=hdx-python-api
48+
git+git://github.com/ocha-dap/hdx-python-api.git@v0.5#egg=hdx-python-api
4949

5050
If you get errors, it is probably the dependencies of the cryptography package that are missing eg. for Ubuntu: python-dev, libffi-dev and libssl-dev. See [cryptography dependencies](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux)
5151

@@ -68,7 +68,7 @@ Let's start with a simple example that also ensures that the library is working
6868
source test/bin/activate
6969
4. Install the HDX Python library:
7070

71-
pip install git+git://github.com/ocha-dap/hdx-python-api.git@v0.42#egg=hdx-python-api
71+
pip install git+git://github.com/ocha-dap/hdx-python-api.git@v0.5#egg=hdx-python-api
7272
5. If you get errors, it is probably the [dependencies of the cryptography package](#installing-the-library)
7373
6. Launch python:
7474

@@ -246,9 +246,9 @@ You can also do so by the standard dictionary `update` method, which takes a d
246246

247247
Larger amounts of static metadata are best added from files. YAML is very human readable and recommended, while JSON is also accepted eg.
248248

249-
dataset.update_yaml([path])
249+
dataset.update_from_yaml([path])
250250

251-
dataset.update_json([path])
251+
dataset.update_from_json([path])
252252

253253
The default path if unspecified is `config/hdx_TYPE_static.yml` for YAML and `config/hdx_TYPE_static.json` for JSON where TYPE is an HDX object's type like dataset or resource eg. `config/hdx_galleryitem_static.json`. The YAML file takes the following form:
254254

@@ -328,7 +328,7 @@ Next create a file called `run.py` and copy into it the code below.
328328
'''
329329
import logging
330330
from hdx.facades.scraperwiki import facade
331-
from my_code import generate_dataset
331+
from .my_code import generate_dataset
332332

333333
logger = logging.getLogger(__name__)
334334

hdx/data/dataset.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ def get_gallery(self) -> List[GalleryItem]:
211211
"""
212212
return self.gallery
213213

214-
def update_yaml(self, path: Optional[str] = join('config', 'hdx_dataset_static.yml')) -> None:
214+
def update_from_yaml(self, path: Optional[str] = join('config', 'hdx_dataset_static.yml')) -> None:
215215
"""Update dataset metadata with static metadata from YAML file
216216
217217
Args:
@@ -220,11 +220,11 @@ def update_yaml(self, path: Optional[str] = join('config', 'hdx_dataset_static.y
220220
Returns:
221221
None
222222
"""
223-
super(Dataset, self).update_yaml(path)
223+
super(Dataset, self).update_from_yaml(path)
224224
self.separate_resources()
225225
self.separate_gallery()
226226

227-
def update_json(self, path: Optional[str] = join('config', 'hdx_dataset_static.json')) -> None:
227+
def update_from_json(self, path: Optional[str] = join('config', 'hdx_dataset_static.json')) -> None:
228228
"""Update dataset metadata with static metadata from JSON file
229229
230230
Args:
@@ -233,7 +233,7 @@ def update_json(self, path: Optional[str] = join('config', 'hdx_dataset_static.j
233233
Returns:
234234
None
235235
"""
236-
super(Dataset, self).update_json(path)
236+
super(Dataset, self).update_from_json(path)
237237
self.separate_resources()
238238
self.separate_gallery()
239239

@@ -453,4 +453,6 @@ def search_in_hdx(configuration: Configuration, query: str) -> List['Dataset']:
453453
dataset.data = datasetdict
454454
dataset._dataset_create_resources_gallery()
455455
datasets.append(dataset)
456+
else:
457+
logger.debug(result)
456458
return datasets

hdx/data/galleryitem.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
"""GalleryItem class containing all logic for creating, checking, and updating gallery items."""
44
import logging
55
from os.path import join
6-
76
from typing import Optional, List
87

98
from hdx.configuration import Configuration
@@ -39,7 +38,7 @@ def actions() -> dict:
3938
'list': 'related_list'
4039
}
4140

42-
def update_yaml(self, path: str = join('config', 'hdx_galleryitem_static.yml')) -> None:
41+
def update_from_yaml(self, path: str = join('config', 'hdx_galleryitem_static.yml')) -> None:
4342
"""Update gallery item metadata with static metadata from YAML file
4443
4544
Args:
@@ -48,9 +47,9 @@ def update_yaml(self, path: str = join('config', 'hdx_galleryitem_static.yml'))
4847
Returns:
4948
None
5049
"""
51-
super(GalleryItem, self).update_yaml(path)
50+
super(GalleryItem, self).update_from_yaml(path)
5251

53-
def update_json(self, path: str = join('config', 'hdx_galleryitem_static.json')) -> None:
52+
def update_from_json(self, path: str = join('config', 'hdx_galleryitem_static.json')) -> None:
5453
"""Update gallery item metadata with static metadata from JSON file
5554
5655
Args:
@@ -59,7 +58,7 @@ def update_json(self, path: str = join('config', 'hdx_galleryitem_static.json'))
5958
Returns:
6059
None
6160
"""
62-
super(GalleryItem, self).update_json(path)
61+
super(GalleryItem, self).update_from_json(path)
6362

6463
@staticmethod
6564
def read_from_hdx(configuration: Configuration, identifier: str) -> Optional['GalleryItem']:

hdx/data/hdxobject.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def get_old_data_dict(self) -> None:
6060
"""
6161
return self.old_data
6262

63-
def update_yaml(self, path: str) -> None:
63+
def update_from_yaml(self, path: str) -> None:
6464
"""Update metadata with static metadata from YAML file
6565
6666
Args:
@@ -71,7 +71,7 @@ def update_yaml(self, path: str) -> None:
7171
"""
7272
self.data = load_yaml_into_existing_dict(self.data, path)
7373

74-
def update_json(self, path: str):
74+
def update_from_json(self, path: str):
7575
"""Update metadata with static metadata from JSON file
7676
7777
Args:
@@ -83,17 +83,19 @@ def update_json(self, path: str):
8383
self.data = load_json_into_existing_dict(self.data, path)
8484

8585
def _read_from_hdx(self, object_type: str, value: str, fieldname: Optional[str] = 'id',
86-
action: Optional[str] = None) -> Tuple[bool, dict]:
86+
action: Optional[str] = None,
87+
other_fields: dict = {}) -> Union[Tuple[bool, dict], Tuple[bool, str]]:
8788
"""Makes a read call to HDX passing in given parameter.
8889
8990
Args:
9091
object_type (str): Description of HDX object type (for messages)
9192
value (str): Value of HDX field
9293
fieldname (Optional[str]): HDX field name. Defaults to id.
9394
action (Optional[str]): Replacement CKAN action url to use. Defaults to None.
95+
other_fields (dict): Other fields to pass to CKAN. Defaults to empty dict.
9496
9597
Returns:
96-
(bool, dict): (True/False, HDX object metadata/Error)
98+
(bool, dict/str): (True/False, HDX object metadata/Error)
9799
"""
98100
if not value:
99101
raise HDXError("Empty %s value!" % object_type)
@@ -102,14 +104,16 @@ def _read_from_hdx(self, object_type: str, value: str, fieldname: Optional[str]
102104
action = self.actions()['search']
103105
else:
104106
action = self.actions()['show']
107+
data = {fieldname: value}
108+
data.update(other_fields)
105109
try:
106-
result = self.hdxpostsite.call_action(action, {fieldname: value},
110+
result = self.hdxpostsite.call_action(action, data,
107111
requests_kwargs={'auth': self.configuration._get_credentials()})
108112
return True, result
109-
except NotFound as e:
113+
except NotFound:
110114
return False, "%s=%s: not found!" % (fieldname, value)
111115
except Exception as e:
112-
raise HDXError('HTTP Get failed when trying to read: %s=%s' % (fieldname, value)) from e
116+
raise HDXError('HTTP Post failed when trying to read: %s=%s' % (fieldname, value)) from e
113117

114118
def _load_from_hdx(self, object_type: str, id_field: str) -> bool:
115119
"""Helper method to load the HDX object given by identifier from HDX
@@ -126,6 +130,7 @@ def _load_from_hdx(self, object_type: str, id_field: str) -> bool:
126130
self.old_data = self.data
127131
self.data = result
128132
return True
133+
logger.debug(result)
129134
return False
130135

131136
@staticmethod
@@ -224,21 +229,20 @@ def _update_in_hdx(self, object_type: str, id_field_name: str) -> None:
224229
self._check_load_existing_object(object_type, id_field_name)
225230
self._merge_hdx_update(object_type, id_field_name)
226231

227-
def _write_to_hdx(self, action: str, data: dict, id_field_name: str) -> Union[Tuple[bool, dict], Tuple[bool, str]]:
232+
def _write_to_hdx(self, action: str, data: dict, id_field_name: str) -> dict:
228233
"""Creates or updates an HDX object in HDX and return HDX object metadata dict
229234
230235
Args:
231-
action (str): Action to perform: 'create' or 'update'
236+
action (str): Action to perform eg. 'create', 'update'
232237
data (dict): Data to write to HDX
233238
id_field_name (str): Name of field containing HDX object identifier
234239
235240
Returns:
236-
(bool, dict): (True/False, HDX object metadata/Error)
241+
dict: HDX object metadata
237242
"""
238243
try:
239-
result = self.hdxpostsite.call_action(self.actions()[action], data,
240-
requests_kwargs={'auth': self.configuration._get_credentials()})
241-
return True, result
244+
return self.hdxpostsite.call_action(self.actions()[action], data,
245+
requests_kwargs={'auth': self.configuration._get_credentials()})
242246
except Exception as e:
243247
raise HDXError('HTTP Post failed when trying to %s %s' % (action, self.data[id_field_name])) from e
244248

@@ -253,13 +257,9 @@ def _save_to_hdx(self, action: str, id_field_name: str) -> None:
253257
Returns:
254258
None
255259
"""
256-
success, result = self._write_to_hdx(action, self.data, id_field_name)
257-
258-
if success:
259-
self.old_data = self.data
260-
self.data = result
261-
else:
262-
raise HDXError('Failed to %s %s\n%s' % (action, self.data[id_field_name], result))
260+
result = self._write_to_hdx(action, self.data, id_field_name)
261+
self.old_data = self.data
262+
self.data = result
263263

264264
@abc.abstractmethod
265265
def create_in_hdx(self) -> None:

0 commit comments

Comments
 (0)