-
Notifications
You must be signed in to change notification settings - Fork 141
/
_json.py
348 lines (279 loc) · 12.7 KB
/
_json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from builtins import str
import json
import logging
from hashlib import sha1
import traceback
import uuid
import requests
from ckan import model
from ckan import logic
from ckan import plugins as p
from ckanext.harvest.model import HarvestObject, HarvestObjectExtra
from ckanext.harvest.logic.schema import unicode_safe
from ckanext.dcat import converters
from ckanext.dcat.harvesters.base import DCATHarvester
log = logging.getLogger(__name__)
class DCATJSONHarvester(DCATHarvester):
def info(self):
return {
'name': 'dcat_json',
'title': 'DCAT JSON Harvester',
'description': 'Harvester for DCAT dataset descriptions ' +
'serialized as JSON'
}
def _get_guids_and_datasets(self, content):
doc = json.loads(content)
if isinstance(doc, list):
# Assume a list of datasets
datasets = doc
elif isinstance(doc, dict):
datasets = doc.get('dataset', [])
else:
raise ValueError('Wrong JSON object')
for dataset in datasets:
as_string = json.dumps(dataset)
# Get identifier
guid = dataset.get('identifier')
if not guid:
# This is bad, any ideas welcomed
guid = sha1(as_string).hexdigest()
yield guid, as_string
def _get_package_dict(self, harvest_object):
content = harvest_object.content
dcat_dict = json.loads(content)
package_dict = converters.dcat_to_ckan(dcat_dict)
return package_dict, dcat_dict
def gather_stage(self, harvest_job):
log.debug('In DCATJSONHarvester gather_stage')
ids = []
# Get the previous guids for this source
query = \
model.Session.query(HarvestObject.guid, HarvestObject.package_id) \
.filter(HarvestObject.current == True) \
.filter(HarvestObject.harvest_source_id == harvest_job.source.id)
guid_to_package_id = {}
for guid, package_id in query:
guid_to_package_id[guid] = package_id
guids_in_db = list(guid_to_package_id.keys())
guids_in_source = []
# Get file contents
url = harvest_job.source.url
previous_guids = []
page = 1
while True:
try:
content, content_type = \
self._get_content_and_type(url, harvest_job, page)
except requests.exceptions.HTTPError as error:
if error.response.status_code == 404:
if page > 1:
# Server returned a 404 after the first page, no more
# records
log.debug('404 after first page, no more pages')
break
else:
# Proper 404
msg = 'Could not get content. Server responded with ' \
'404 Not Found'
self._save_gather_error(msg, harvest_job)
return None
else:
# This should never happen. Raising just in case.
raise
if not content:
return None
try:
batch_guids = []
for guid, as_string in self._get_guids_and_datasets(content):
log.debug('Got identifier: {0}'
.format(guid.encode('utf8')))
batch_guids.append(guid)
if guid not in previous_guids:
if guid in guids_in_db:
# Dataset needs to be udpated
obj = HarvestObject(
guid=guid, job=harvest_job,
package_id=guid_to_package_id[guid],
content=as_string,
extras=[HarvestObjectExtra(key='status',
value='change')])
else:
# Dataset needs to be created
obj = HarvestObject(
guid=guid, job=harvest_job,
content=as_string,
extras=[HarvestObjectExtra(key='status',
value='new')])
obj.save()
ids.append(obj.id)
if len(batch_guids) > 0:
guids_in_source.extend(set(batch_guids)
- set(previous_guids))
else:
log.debug('Empty document, no more records')
# Empty document, no more ids
break
except ValueError as e:
msg = 'Error parsing file: {0}'.format(str(e))
self._save_gather_error(msg, harvest_job)
return None
if sorted(previous_guids) == sorted(batch_guids):
# Server does not support pagination or no more pages
log.debug('Same content, no more pages')
break
page = page + 1
previous_guids = batch_guids
# Check datasets that need to be deleted
guids_to_delete = set(guids_in_db) - set(guids_in_source)
for guid in guids_to_delete:
obj = HarvestObject(
guid=guid, job=harvest_job,
package_id=guid_to_package_id[guid],
extras=[HarvestObjectExtra(key='status', value='delete')])
ids.append(obj.id)
model.Session.query(HarvestObject).\
filter_by(guid=guid).\
update({'current': False}, False)
obj.save()
return ids
def fetch_stage(self, harvest_object):
return True
def import_stage(self, harvest_object):
log.debug('In DCATJSONHarvester import_stage')
if not harvest_object:
log.error('No harvest object received')
return False
if self.force_import:
status = 'change'
else:
status = self._get_object_extra(harvest_object, 'status')
if status == 'delete':
# Delete package
context = {'model': model, 'session': model.Session,
'user': self._get_user_name()}
p.toolkit.get_action('package_delete')(
context, {'id': harvest_object.package_id})
log.info('Deleted package {0} with guid {1}'
.format(harvest_object.package_id, harvest_object.guid))
return True
if harvest_object.content is None:
self._save_object_error(
'Empty content for object %s' % harvest_object.id,
harvest_object, 'Import')
return False
# Get the last harvested object (if any)
previous_object = model.Session.query(HarvestObject) \
.filter(HarvestObject.guid == harvest_object.guid) \
.filter(HarvestObject.current == True) \
.first()
# Flag previous object as not current anymore
if previous_object and not self.force_import:
previous_object.current = False
previous_object.add()
package_dict, dcat_dict = self._get_package_dict(harvest_object)
if not package_dict:
return False
if not package_dict.get('name'):
package_dict['name'] = \
self._get_package_name(harvest_object, package_dict['title'])
# copy across resource ids from the existing dataset, otherwise they'll
# be recreated with new ids
if status == 'change':
existing_dataset = self._get_existing_dataset(harvest_object.guid)
if existing_dataset:
copy_across_resource_ids(existing_dataset, package_dict)
# Allow custom harvesters to modify the package dict before creating
# or updating the package
package_dict = self.modify_package_dict(package_dict,
dcat_dict,
harvest_object)
# Unless already set by an extension, get the owner organization (if
# any) from the harvest source dataset
if not package_dict.get('owner_org'):
source_dataset = model.Package.get(harvest_object.source.id)
if source_dataset.owner_org:
package_dict['owner_org'] = source_dataset.owner_org
# Flag this object as the current one
harvest_object.current = True
harvest_object.add()
context = {
'user': self._get_user_name(),
'return_id_only': True,
'ignore_auth': True,
}
try:
if status == 'new':
package_schema = logic.schema.default_create_package_schema()
context['schema'] = package_schema
# We need to explicitly provide a package ID
package_dict['id'] = str(uuid.uuid4())
package_schema['id'] = [unicode_safe]
# Save reference to the package on the object
harvest_object.package_id = package_dict['id']
harvest_object.add()
# Defer constraints and flush so the dataset can be indexed with
# the harvest object id (on the after_show hook from the harvester
# plugin)
model.Session.execute(
'SET CONSTRAINTS harvest_object_package_id_fkey DEFERRED')
model.Session.flush()
elif status == 'change':
package_dict['id'] = harvest_object.package_id
if status in ['new', 'change']:
action = 'package_create' if status == 'new' else 'package_update'
message_status = 'Created' if status == 'new' else 'Updated'
package_id = p.toolkit.get_action(action)(context, package_dict)
log.info('%s dataset with id %s', message_status, package_id)
except Exception as e:
dataset = json.loads(harvest_object.content)
dataset_name = dataset.get('name', '')
self._save_object_error('Error importing dataset %s: %r / %s' % (dataset_name, e, traceback.format_exc()), harvest_object, 'Import')
return False
finally:
model.Session.commit()
return True
def copy_across_resource_ids(existing_dataset, harvested_dataset):
'''Compare the resources in a dataset existing in the CKAN database with
the resources in a freshly harvested copy, and for any resources that are
the same, copy the resource ID into the harvested_dataset dict.
'''
# take a copy of the existing_resources so we can remove them when they are
# matched - we don't want to match them more than once.
existing_resources_still_to_match = \
[r for r in existing_dataset.get('resources')]
# we match resources a number of ways. we'll compute an 'identity' of a
# resource in both datasets and see if they match.
# start with the surest way of identifying a resource, before reverting
# to closest matches.
resource_identity_functions = [
lambda r: r['uri'], # URI is best
lambda r: (r['url'], r['title'], r['format']),
lambda r: (r['url'], r['title']),
lambda r: r['url'], # same URL is fine if nothing else matches
]
for resource_identity_function in resource_identity_functions:
# calculate the identities of the existing_resources
existing_resource_identities = {}
for r in existing_resources_still_to_match:
try:
identity = resource_identity_function(r)
existing_resource_identities[identity] = r
except KeyError:
pass
# calculate the identities of the harvested_resources
for resource in harvested_dataset.get('resources'):
try:
identity = resource_identity_function(resource)
except KeyError:
identity = None
if identity and identity in existing_resource_identities:
# we got a match with the existing_resources - copy the id
matching_existing_resource = \
existing_resource_identities[identity]
resource['id'] = matching_existing_resource['id']
# make sure we don't match this existing_resource again
del existing_resource_identities[identity]
existing_resources_still_to_match.remove(
matching_existing_resource)
if not existing_resources_still_to_match:
break