-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUSGINharvestHelpers.py
2758 lines (2302 loc) · 102 KB
/
USGINharvestHelpers.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
# # Imports
# In[1]:
#import cgitb
import datetime
import dateutil
#import hashlib
import logging
#import mimetypes
import re
import requests
import sys
import urllib
import urllib2
import urlparse
import uuid
import warnings
from string import Template
from urlparse import urlparse
from datetime import datetime
#from pylons import config
from owslib import wms
from lxml import etree
#from sqlalchemy import event
#from sqlalchemy import distinct
#from sqlalchemy import Table
#from sqlalchemy import Column
#from sqlalchemy import ForeignKey
#from sqlalchemy import types
#from sqlalchemy import Index
#from sqlalchemy.engine.reflection import Inspector
#from sqlalchemy.orm import backref, relation
#from sqlalchemy.exc import InvalidRequestError
#from sqlalchemy import exists
#from sqlalchemy.sql import update, bindparam
from ckan import plugins as p
from ckan import model
from ckan import logic
#from ckan.model import Session
#from ckan.model import Package
#from ckan.model import PACKAGE_NAME_MAX_LENGTH
#from ckan.model.meta import metadata
from ckan.model.meta import mapper
#from ckan.model.meta import Session
from ckan.model.types import make_uuid
from ckan.model.domain_object import DomainObject
#from ckan.model.package import Package
from ckan.plugins.interfaces import Interface
from ckan.plugins.core import SingletonPlugin
from ckan.plugins.core import implements
from ckan.logic.schema import default_create_package_schema
from ckan.lib.navl.validators import ignore_missing
from ckan.lib.navl.validators import ignore
from ckan.lib.navl.validators import not_empty
from ckan.lib.munge import munge_title_to_name
from ckan.lib.munge import substitute_ascii_equivalents
#from ckan.lib.helpers import json
#from ckan.lib.search.index import PackageSearchIndex
# # Harvest interfaces
# In[2]:
get_ipython().magic(u'pinfo2 IHarvester')
# In[3]:
# %load E:\GitHub\ckan\ckanext-harvest\ckanext\harvest\interfaces.py
class IHarvester(Interface):
'''
Common harvesting interface
'''
def info(self):
'''
place holder
'''
def validate_config(self, config):
'''
place holder
'''
def get_original_url(self, harvest_object_id):
'''
place holder
'''
def gather_stage(self, harvest_job):
'''
place holder
'''
def fetch_stage(self, harvest_object):
'''
place holder
'''
def import_stage(self, harvest_object):
'''
place holder
'''
# # Harvest model init
# In[4]:
# %load E:\GitHub\ckan\ckanext-harvest\ckanext\harvest\model\__init__.py
UPDATE_FREQUENCIES = ['MANUAL','MONTHLY','WEEKLY','BIWEEKLY','DAILY', 'ALWAYS']
log = logging.getLogger(__name__)
__all__ = [
'HarvestSource', 'harvest_source_table',
'HarvestJob', 'harvest_job_table',
'HarvestObject', 'harvest_object_table',
'HarvestGatherError', 'harvest_gather_error_table',
'HarvestObjectError', 'harvest_object_error_table',
'HarvestLog', 'harvest_log_table'
]
harvest_source_table = None
harvest_job_table = None
harvest_object_table = None
harvest_gather_error_table = None
harvest_object_error_table = None
harvest_object_extra_table = None
harvest_log_table = None
def setup():
pass
"""if harvest_source_table is None:
define_harvester_tables()
log.debug('Harvest tables defined in memory')
if not model.package_table.exists():
log.debug('Harvest table creation deferred')
return
if not harvest_source_table.exists():
# Create each table individually rather than
# using metadata.create_all()
harvest_source_table.create()
harvest_job_table.create()
harvest_object_table.create()
harvest_gather_error_table.create()
harvest_object_error_table.create()
harvest_object_extra_table.create()
harvest_log_table.create()
log.debug('Harvest tables created')
else:
from ckan.model.meta import engine
log.debug('Harvest tables already exist')
# Check if existing tables need to be updated
inspector = Inspector.from_engine(engine)
columns = inspector.get_columns('harvest_source')
column_names = [column['name'] for column in columns]
if not 'title' in column_names:
log.debug('Harvest tables need to be updated')
migrate_v2()
if not 'frequency' in column_names:
log.debug('Harvest tables need to be updated')
migrate_v3()
# Check if this instance has harvest source datasets
source_ids = Session.query(HarvestSource.id).filter_by(active=True).all()
source_package_ids = Session.query(model.Package.id).filter_by(type=u'harvest', state='active').all()
sources_to_migrate = set(source_ids) - set(source_package_ids)
if sources_to_migrate:
log.debug('Creating harvest source datasets for %i existing sources', len(sources_to_migrate))
sources_to_migrate = [s[0] for s in sources_to_migrate]
migrate_v3_create_datasets(sources_to_migrate)
# Check if harvest_log table exist - needed for existing users
if not 'harvest_log' in inspector.get_table_names():
harvest_log_table.create()
# Check if harvest_object has a index
index_names = [index['name'] for index in inspector.get_indexes("harvest_object")]
if not "harvest_job_id_idx" in index_names:
log.debug('Creating index for harvest_object')
Index("harvest_job_id_idx", harvest_object_table.c.harvest_job_id).create()"""
class HarvestError(Exception):
pass
class HarvestDomainObject(DomainObject):
'''Convenience methods for searching objects
'''
key_attr = 'id'
@classmethod
def get(cls, key, default=None, attr=None):
'''Finds a single entity in the register.'''
if attr == None:
attr = cls.key_attr
kwds = {attr: key}
o = cls.filter(**kwds).first()
if o:
return o
else:
return default
@classmethod
def filter(cls, **kwds):
query = Session.query(cls).autoflush(False)
return query.filter_by(**kwds)
class HarvestSource(HarvestDomainObject):
'''A Harvest Source is essentially a URL plus some other metadata.
It must have a type (e.g. CSW) and can have a status of "active"
or "inactive". The harvesting processes are not fired on inactive
sources.
'''
def __repr__(self):
return '<HarvestSource id=%s title=%s url=%s active=%r>' % (self.id, self.title, self.url, self.active)
def __str__(self):
return self.__repr__().encode('ascii', 'ignore')
class HarvestJob(HarvestDomainObject):
'''A Harvesting Job is performed in two phases. In first place, the
**gather** stage collects all the Ids and URLs that need to be fetched
from the harvest source. Errors occurring in this phase
(``HarvestGatherError``) are stored in the ``harvest_gather_error``
table. During the next phase, the **fetch** stage retrieves the
``HarvestedObjects`` and, if necessary, the **import** stage stores
them on the database. Errors occurring in this second stage
(``HarvestObjectError``) are stored in the ``harvest_object_error``
table.
'''
pass
class HarvestObject(HarvestDomainObject):
'''A Harvest Object is created every time an element is fetched from a
harvest source. Its contents can be processed and imported to ckan
packages, RDF graphs, etc.
'''
class HarvestObjectExtra(HarvestDomainObject):
'''Extra key value data for Harvest objects'''
class HarvestGatherError(HarvestDomainObject):
'''Gather errors are raised during the **gather** stage of a harvesting
job.
'''
@classmethod
def create(cls, message, job):
'''
Helper function to create an error object and save it.
'''
err = cls(message=message, job=job)
try:
err.save()
except InvalidRequestError:
Session.rollback()
err.save()
finally:
# No need to alert administrator so don't log as an error
log.info(message)
class HarvestObjectError(HarvestDomainObject):
'''Object errors are raised during the **fetch** or **import** stage of a
harvesting job, and are referenced to a specific harvest object.
'''
@classmethod
def create(cls, message, object, stage=u'Fetch', line=None):
'''
Helper function to create an error object and save it.
'''
err = cls(message=message, object=object,
stage=stage, line=line)
try:
err.save()
except InvalidRequestError, e:
# Clear any in-progress sqlalchemy transactions
try:
Session.rollback()
except:
pass
try:
Session.remove()
except:
pass
err.save()
finally:
log_message = '{0}, line {1}'.format(message, line) if line else message
log.debug(log_message)
class HarvestLog(HarvestDomainObject):
'''HarvestLog objects are created each time something is logged
using python's standard logging module
'''
pass
def harvest_object_before_insert_listener(mapper,connection,target):
'''
For compatibility with old harvesters, check if the source id has
been set, and set it automatically from the job if not.
'''
if not target.harvest_source_id or not target.source:
if not target.job:
raise Exception('You must define a Harvest Job for each Harvest Object')
target.source = target.job.source
target.harvest_source_id = target.job.source.id
def define_harvester_tables():
pass
"""
remove content
"""
def migrate_v2():
pass
"""
remove content--not using
"""
def migrate_v3():
pass
"""
remove content, not using
"""
class PackageIdHarvestSourceIdMismatch(Exception):
"""
The package created for the harvest source must match the id of the
harvest source
"""
pass
def migrate_v3_create_datasets(source_ids=None):
pass
"""
remove content
"""
def clean_harvest_log(condition):
pass
"""
remove content
"""
# # Harvest base
# In[5]:
# %load E:\GitHub\ckan\ckanext-harvest\ckanext\harvest\harvesters\base.py
#smr from ckanext.harvest.model import (HarvestObject, HarvestGatherError, HarvestObjectError, HarvestJob)
#import HarvestObject, HarvestGatherError, HarvestObjectError, HarvestJob
#from ckanext.harvest.interfaces import IHarvester
"""
SMR comment this out and use the else option; this introduces dependency on repoze.who.config
which doesn't want to pip install
if p.toolkit.check_ckan_version(min_version='2.3'):
from ckan.lib.munge import munge_tag
else:
# Fallback munge_tag for older ckan versions which don't have a decent
# munger
"""
def _munge_to_length(string, min_length, max_length):
'''Pad/truncates a string'''
if len(string) < min_length:
string += '_' * (min_length - len(string))
if len(string) > max_length:
string = string[:max_length]
return string
def munge_tag(tag):
tag = substitute_ascii_equivalents(tag)
tag = tag.lower().strip()
tag = re.sub(r'[^a-zA-Z0-9\- ]', '', tag).replace(' ', '-')
tag = _munge_to_length(tag, model.MIN_TAG_LENGTH, model.MAX_TAG_LENGTH)
return tag
# end SMR adjustment
log = logging.getLogger(__name__)
class HarvesterBase(SingletonPlugin):
'''
Generic base class for harvesters, providing a number of useful functions.
A harvester doesn't have to derive from this - it could just have:
implements(IHarvester)
'''
implements(IHarvester)
config = None
_user_name = None
@classmethod
def _gen_new_name(cls, title, existing_name=None,
append_type=None):
'''
Returns a 'name' for the dataset (URL friendly), based on the title.
If the ideal name is already used, it will append a number to it to
ensure it is unique.
If generating a new name because the title of the dataset has changed,
specify the existing name, in case the name doesn't need to change
after all.
:param existing_name: the current name of the dataset - only specify
this if the dataset exists
:type existing_name: string
:param append_type: the type of characters to add to make it unique -
either 'number-sequence' or 'random-hex'.
:type append_type: string
'''
# If append_type was given, use it. Otherwise, use the configured default.
# If nothing was given and no defaults were set, use 'number-sequence'.
if append_type:
append_type_param = append_type
else:
append_type_param = config.get('ckanext.harvest.default_dataset_name_append',
'number-sequence')
ideal_name = munge_title_to_name(title)
ideal_name = re.sub('-+', '-', ideal_name) # collapse multiple dashes
return cls._ensure_name_is_unique(ideal_name,
existing_name=existing_name,
append_type=append_type_param)
@staticmethod
def _ensure_name_is_unique(ideal_name, existing_name=None,
append_type='number-sequence'):
'''
Returns a dataset name based on the ideal_name, only it will be
guaranteed to be different than all the other datasets, by adding a
number on the end if necessary.
If generating a new name because the title of the dataset has changed,
specify the existing name, in case the name doesn't need to change
after all.
The maximum dataset name length is taken account of.
:param ideal_name: the desired name for the dataset, if its not already
been taken (usually derived by munging the dataset
title)
:type ideal_name: string
:param existing_name: the current name of the dataset - only specify
this if the dataset exists
:type existing_name: string
:param append_type: the type of characters to add to make it unique -
either 'number-sequence' or 'random-hex'.
:type append_type: string
'''
ideal_name = ideal_name[:PACKAGE_NAME_MAX_LENGTH]
if existing_name == ideal_name:
return ideal_name
if append_type == 'number-sequence':
MAX_NUMBER_APPENDED = 999
APPEND_MAX_CHARS = len(str(MAX_NUMBER_APPENDED))
elif append_type == 'random-hex':
APPEND_MAX_CHARS = 5 # 16^5 = 1 million combinations
else:
raise NotImplementedError('append_type cannot be %s' % append_type)
# Find out which package names have been taken. Restrict it to names
# derived from the ideal name plus and numbers added
like_q = u'%s%%' % ideal_name[:PACKAGE_NAME_MAX_LENGTH-APPEND_MAX_CHARS]
name_results = Session.query(Package.name) .filter(Package.name.ilike(like_q)) .all()
taken = set([name_result[0] for name_result in name_results])
if existing_name and existing_name in taken:
taken.remove(existing_name)
if ideal_name not in taken:
# great, the ideal name is available
return ideal_name
elif existing_name and existing_name.startswith(ideal_name):
# the ideal name is not available, but its an existing dataset with
# a name based on the ideal one, so there's no point changing it to
# a different number
return existing_name
elif append_type == 'number-sequence':
# find the next available number
counter = 1
while counter <= MAX_NUMBER_APPENDED:
candidate_name = ideal_name[:PACKAGE_NAME_MAX_LENGTH-len(str(counter))] + str(counter)
if candidate_name not in taken:
return candidate_name
counter = counter + 1
return None
elif append_type == 'random-hex':
return ideal_name[:PACKAGE_NAME_MAX_LENGTH-APPEND_MAX_CHARS] + str(uuid.uuid4())[:APPEND_MAX_CHARS]
_save_gather_error = HarvestGatherError.create
_save_object_error = HarvestObjectError.create
def _get_user_name(self):
'''
Returns the name of the user that will perform the harvesting actions
(deleting, updating and creating datasets)
By default this will be the old 'harvest' user to maintain
compatibility. If not present, the internal site admin user will be
used. This is the recommended setting, but if necessary it can be
overridden with the `ckanext.harvest.user_name` config option:
ckanext.harvest.user_name = harvest
'''
if self._user_name:
return self._user_name
config_user_name = config.get('ckanext.harvest.user_name')
if config_user_name:
self._user_name = config_user_name
return self._user_name
context = {'model': model,
'ignore_auth': True,
}
# Check if 'harvest' user exists and if is a sysadmin
try:
user_harvest = p.toolkit.get_action('user_show')(
context, {'id': 'harvest'})
if user_harvest['sysadmin']:
self._user_name = 'harvest'
return self._user_name
except p.toolkit.ObjectNotFound:
pass
context['defer_commit'] = True # See ckan/ckan#1714
self._site_user = p.toolkit.get_action('get_site_user')(context, {})
self._user_name = self._site_user['name']
return self._user_name
def _create_harvest_objects(self, remote_ids, harvest_job):
'''
Given a list of remote ids and a Harvest Job, create as many Harvest Objects and
return a list of their ids to be passed to the fetch stage.
TODO: Not sure it is worth keeping this function
'''
try:
object_ids = []
if len(remote_ids):
for remote_id in remote_ids:
# Create a new HarvestObject for this identifier
obj = HarvestObject(guid = remote_id, job = harvest_job)
obj.save()
object_ids.append(obj.id)
return object_ids
else:
self._save_gather_error('No remote datasets could be identified', harvest_job)
except Exception, e:
self._save_gather_error('%r' % e.message, harvest_job)
def _create_or_update_package(self, package_dict, harvest_object,
package_dict_form='rest'):
'''
Creates a new package or updates an existing one according to the
package dictionary provided.
The package dictionary can be in one of two forms:
1. 'rest' - as seen on the RESTful API:
http://datahub.io/api/rest/dataset/1996_population_census_data_canada
This is the legacy form. It is the default to provide backward
compatibility.
* 'extras' is a dict e.g. {'theme': 'health', 'sub-theme': 'cancer'}
* 'tags' is a list of strings e.g. ['large-river', 'flood']
2. 'package_show' form, as provided by the Action API (CKAN v2.0+):
http://datahub.io/api/action/package_show?id=1996_population_census_data_canada
* 'extras' is a list of dicts
e.g. [{'key': 'theme', 'value': 'health'},
{'key': 'sub-theme', 'value': 'cancer'}]
* 'tags' is a list of dicts
e.g. [{'name': 'large-river'}, {'name': 'flood'}]
Note that the package_dict must contain an id, which will be used to
check if the package needs to be created or updated (use the remote
dataset id).
If the remote server provides the modification date of the remote
package, add it to package_dict['metadata_modified'].
:returns: The same as what import_stage should return. i.e. True if the
create or update occurred ok, 'unchanged' if it didn't need
updating or False if there were errors.
TODO: Not sure it is worth keeping this function. If useful it should
use the output of package_show logic function (maybe keeping support
for rest api based dicts
'''
assert package_dict_form in ('rest', 'package_show')
try:
# Change default schema
schema = default_create_package_schema()
schema['id'] = [ignore_missing, unicode]
schema['__junk'] = [ignore]
# Check API version
if self.config:
try:
api_version = int(self.config.get('api_version', 2))
except ValueError:
raise ValueError('api_version must be an integer')
else:
api_version = 2
user_name = self._get_user_name()
context = {
'model': model,
'session': Session,
'user': user_name,
'api_version': api_version,
'schema': schema,
'ignore_auth': True,
}
if self.config and self.config.get('clean_tags', False):
tags = package_dict.get('tags', [])
package_dict['tags'] = self._clean_tags(tags)
# Check if package exists
try:
# _find_existing_package can be overridden if necessary
existing_package_dict = self._find_existing_package(package_dict)
# In case name has been modified when first importing. See issue #101.
package_dict['name'] = existing_package_dict['name']
# Check modified date
if not 'metadata_modified' in package_dict or package_dict['metadata_modified'] > existing_package_dict.get('metadata_modified'):
log.info('Package with GUID %s exists and needs to be updated' % harvest_object.guid)
# Update package
context.update({'id':package_dict['id']})
package_dict.setdefault('name',
existing_package_dict['name'])
new_package = p.toolkit.get_action(
'package_update' if package_dict_form == 'package_show'
else 'package_update_rest')(context, package_dict)
else:
log.info('No changes to package with GUID %s, skipping...' % harvest_object.guid)
# NB harvest_object.current/package_id are not set
return 'unchanged'
# Flag the other objects linking to this package as not current anymore
from ckanext.harvest.model import harvest_object_table
conn = Session.connection()
u = update(harvest_object_table) .where(harvest_object_table.c.package_id==bindparam('b_package_id')) .values(current=False)
conn.execute(u, b_package_id=new_package['id'])
# Flag this as the current harvest object
harvest_object.package_id = new_package['id']
harvest_object.current = True
harvest_object.save()
except p.toolkit.ObjectNotFound:
# Package needs to be created
# Get rid of auth audit on the context otherwise we'll get an
# exception
context.pop('__auth_audit', None)
# Set name for new package to prevent name conflict, see issue #117
if package_dict.get('name', None):
package_dict['name'] = self._gen_new_name(package_dict['name'])
else:
package_dict['name'] = self._gen_new_name(package_dict['title'])
log.info('Package with GUID %s does not exist, let\'s create it' % harvest_object.guid)
harvest_object.current = True
harvest_object.package_id = package_dict['id']
# Defer constraints and flush so the dataset can be indexed with
# the harvest object id (on the after_show hook from the harvester
# plugin)
harvest_object.add()
model.Session.execute('SET CONSTRAINTS harvest_object_package_id_fkey DEFERRED')
model.Session.flush()
new_package = p.toolkit.get_action(
'package_create' if package_dict_form == 'package_show'
else 'package_create_rest')(context, package_dict)
Session.commit()
return True
except p.toolkit.ValidationError, e:
log.exception(e)
self._save_object_error('Invalid package with GUID %s: %r'%(harvest_object.guid,e.error_dict),harvest_object,'Import')
except Exception, e:
log.exception(e)
self._save_object_error('%r'%e,harvest_object,'Import')
return None
def _find_existing_package(self, package_dict):
data_dict = {'id': package_dict['id']}
package_show_context = {'model': model, 'session': Session,
'ignore_auth': True}
return p.toolkit.get_action('package_show')(
package_show_context, data_dict)
def _clean_tags(self, tags):
try:
def _update_tag(tag_dict, key, newvalue):
# update the dict and return it
tag_dict[key] = newvalue
return tag_dict
# assume it's in the package_show form
tags = [_update_tag(t, 'name', munge_tag(t['name'])) for t in tags if munge_tag(t['name']) != '']
except TypeError: # a TypeError is raised if `t` above is a string
# REST format: 'tags' is a list of strings
tags = [munge_tag(t) for t in tags if munge_tag(t) != '']
tags = list(set(tags))
return tags
return tags
@classmethod
def last_error_free_job(cls, harvest_job):
# TODO weed out cancelled jobs somehow.
# look for jobs with no gather errors
jobs = model.Session.query(HarvestJob) .filter(HarvestJob.source == harvest_job.source) .filter(HarvestJob.gather_started != None) .filter(HarvestJob.status == 'Finished') .filter(HarvestJob.id != harvest_job.id) .filter(
~exists().where(
HarvestGatherError.harvest_job_id == HarvestJob.id)) \
.order_by(HarvestJob.gather_started.desc())
# now check them until we find one with no fetch/import errors
# (looping rather than doing sql, in case there are lots of objects
# and lots of jobs)
for job in jobs:
for obj in job.objects:
if obj.current is False and obj.report_status != 'not modified':
# unsuccessful, so go onto the next job
break
else:
return job
# # Model ISO XML metadata
# In[6]:
# Model harvested metadata
# %load E:\GitHub\ckan\ckanext-spatial\ckanext\spatial\model\harvested_metadata.py
log = logging.getLogger(__name__)
class MappedXmlObject(object):
elements = []
class MappedXmlDocument(MappedXmlObject):
def __init__(self, xml_str=None, xml_tree=None):
assert (xml_str or xml_tree is not None), 'Must provide some XML in one format or another'
self.xml_str = xml_str
self.xml_tree = xml_tree
def read_values(self):
'''For all of the elements listed, finds the values of them in the
XML and returns them.'''
values = {}
tree = self.get_xml_tree()
for element in self.elements:
values[element.name] = element.read_value(tree)
self.infer_values(values)
return values
def read_value(self, name):
'''For the given element name, find the value in the XML and return
it.
'''
tree = self.get_xml_tree()
for element in self.elements:
if element.name == name:
return element.read_value(tree)
raise KeyError
def get_xml_tree(self):
if self.xml_tree is None:
parser = etree.XMLParser(remove_blank_text=True)
if type(self.xml_str) == unicode:
xml_str = self.xml_str.encode('utf8')
else:
xml_str = self.xml_str
self.xml_tree = etree.fromstring(xml_str, parser=parser)
return self.xml_tree
def infer_values(self, values):
pass
class MappedXmlElement(MappedXmlObject):
namespaces = {}
def __init__(self, name, search_paths=[], multiplicity="*", elements=[]):
self.name = name
self.search_paths = search_paths
self.multiplicity = multiplicity
self.elements = elements or self.elements
def read_value(self, tree):
values = []
for xpath in self.get_search_paths():
elements = self.get_elements(tree, xpath)
values = self.get_values(elements)
if values:
break
return self.fix_multiplicity(values)
def get_search_paths(self):
if type(self.search_paths) != type([]):
search_paths = [self.search_paths]
else:
search_paths = self.search_paths
return search_paths
def get_elements(self, tree, xpath):
return tree.xpath(xpath, namespaces=self.namespaces)
def get_values(self, elements):
values = []
if len(elements) == 0:
pass
else:
for element in elements:
value = self.get_value(element)
values.append(value)
return values
def get_value(self, element):
if self.elements:
value = {}
for child in self.elements:
value[child.name] = child.read_value(element)
return value
elif type(element) == etree._ElementStringResult:
value = str(element)
elif type(element) == etree._ElementUnicodeResult:
value = unicode(element)
else:
value = self.element_tostring(element)
return value
def element_tostring(self, element):
return etree.tostring(element, pretty_print=False)
def fix_multiplicity(self, values):
'''
When a field contains multiple values, yet the spec says
it should contain only one, then return just the first value,
rather than a list.
In the ISO19115 specification, multiplicity relates to:
* 'Association Cardinality'
* 'Obligation/Condition' & 'Maximum Occurence'
'''
if self.multiplicity == "0":
# 0 = None
if values:
log.warn("Values found for element '%s' when multiplicity should be 0: %s", self.name, values)
return ""
elif self.multiplicity == "1":
# 1 = Mandatory, maximum 1 = Exactly one
if not values:
log.warn("Value not found for element '%s'" % self.name)
return ''
return values[0]
elif self.multiplicity == "*":
# * = 0..* = zero or more
return values
elif self.multiplicity == "0..1":
# 0..1 = Mandatory, maximum 1 = optional (zero or one)
if values:
return values[0]
else:
return ""
elif self.multiplicity == "1..*":
# 1..* = one or more
return values
else:
log.warning('Multiplicity not specified for element: %s',
self.name)
return values
class ISOElement(MappedXmlElement):
namespaces = {
"gts": "http://www.isotc211.org/2005/gts",
"gml": "http://www.opengis.net/gml",
"gml32": "http://www.opengis.net/gml/3.2",
"gmx": "http://www.isotc211.org/2005/gmx",
"gsr": "http://www.isotc211.org/2005/gsr",
"gss": "http://www.isotc211.org/2005/gss",
"gco": "http://www.isotc211.org/2005/gco",
"gmd": "http://www.isotc211.org/2005/gmd",
"srv": "http://www.isotc211.org/2005/srv",
"xlink": "http://www.w3.org/1999/xlink",
"xsi": "http://www.w3.org/2001/XMLSchema-instance",
}
class ISOResourceLocator(ISOElement):
elements = [
ISOElement(
name="url",
search_paths=[
"gmd:linkage/gmd:URL/text()",
],
multiplicity="1",
),
ISOElement(
name="function",
search_paths=[
"gmd:function/gmd:CI_OnLineFunctionCode/@codeListValue",
],
multiplicity="0..1",
),
ISOElement(
name="name",
search_paths=[
"gmd:name/gco:CharacterString/text()",
],
multiplicity="0..1",
),
ISOElement(
name="description",
search_paths=[
"gmd:description/gco:CharacterString/text()",
],
multiplicity="0..1",
),
ISOElement(
name="protocol",
search_paths=[
"gmd:protocol/gco:CharacterString/text()",
],
multiplicity="0..1",
),