Skip to content

Commit 1756c1a

Browse files
committed
Add Conditions logic
1 parent a2b30c2 commit 1756c1a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

ckanext/harvest_basket/harvesters/ckan_harvester.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ def import_stage(self, harvest_object):
2121
package_dict = json.loads(harvest_object.content)
2222
self._set_config(harvest_object.source.config)
2323
self.transmute_data(package_dict, self.config.get("tsm_schema"))
24+
self.handle_conditions(
25+
package_dict,
26+
self.config.get("conditions"),
27+
harvest_object.harvest_source_id)
2428
harvest_object.content = json.dumps(package_dict)
2529

2630
super().import_stage(harvest_object)
@@ -67,3 +71,56 @@ def transmute_data(self, data, schema):
6771
},
6872
{"data": data, "schema": schema},
6973
)
74+
75+
def handle_conditions(self, data, conditions, source_id):
76+
'''
77+
Specify conditions for fields, can be multiple conditions
78+
"conditions": [
79+
{"field": "FIELD_NAME",
80+
"source": "harvester_config", If the field should be taken from Harvester Dataset
81+
Otherwise try to take the value from the Data Dict
82+
"case": "FIELD_VALUE_EQUAL",
83+
"then": "FIELD_TO_MODIFY",
84+
"value": "FIELD_TO_MODIFY_VALUE",
85+
"otherwise": "FIELD_TO_DEFAULT" Default value if check not passed. Optional
86+
},
87+
EXAMPLE
88+
{"field": "owner_org",
89+
"source": "harvester_config",
90+
"case": "77f83b6a-8541-4ae8-b439-011ed75b1564",
91+
"then": "groups",
92+
"value": [{"name":"society"}],
93+
"otherwise": [{"id":"transport"}]
94+
}
95+
]
96+
'''
97+
source_dataset = tk.get_action('package_show')(
98+
{
99+
"model": model,
100+
"session": model.Session,
101+
"user": self._get_user_name(),
102+
}, {'id': source_id}
103+
)
104+
105+
for condition in conditions:
106+
try:
107+
field = condition['field']
108+
source = condition.get('source')
109+
case = condition['case']
110+
then = condition['then']
111+
value = condition['value']
112+
otherwise = condition.get('otherwise')
113+
114+
if source and source == 'harvester_config':
115+
val = source_dataset[field]
116+
else:
117+
val = data[field]
118+
119+
if otherwise:
120+
data[then] = value if val == case else otherwise
121+
elif val and val == case:
122+
data[then] = value
123+
except KeyError as e:
124+
err_msg: str = f"Missing key: {e}"
125+
log.error(err_msg)
126+
raise AttributeError(*e.args)

0 commit comments

Comments
 (0)