/
get.py
1387 lines (1079 loc) · 45.5 KB
/
get.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
import uuid
import logging
from pylons import config
from pylons.i18n import _
import webhelpers.html
from sqlalchemy.sql import select
from sqlalchemy.orm import aliased
from sqlalchemy import or_, and_, func, desc, case, text
import ckan
import ckan.authz
import ckan.lib.dictization
import ckan.lib.base
import ckan.logic as logic
import ckan.logic.action
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.lib.navl.dictization_functions
import ckan.model.misc as misc
import ckan.plugins as plugins
import ckan.lib.search as search
import ckan.lib.plugins as lib_plugins
log = logging.getLogger('ckan.logic')
# define some shortcuts
validate = ckan.lib.navl.dictization_functions.validate
table_dictize = ckan.lib.dictization.table_dictize
render = ckan.lib.base.render
Authorizer = ckan.authz.Authorizer
check_access = logic.check_access
NotFound = logic.NotFound
ValidationError = logic.ValidationError
get_or_bust = logic.get_or_bust
def _package_list_with_resources(context, package_revision_list):
package_list = []
model = context["model"]
for package in package_revision_list:
result_dict = model_dictize.package_dictize(package,context)
package_list.append(result_dict)
return package_list
def site_read(context,data_dict=None):
check_access('site_read',context,data_dict)
return True
def package_list(context, data_dict):
'''Lists packages by name or id'''
model = context["model"]
user = context["user"]
api = context.get("api_version", 1)
ref_package_by = 'id' if api == 2 else 'name'
check_access('package_list', context, data_dict)
query = model.Session.query(model.PackageRevision)
query = query.filter(model.PackageRevision.state=='active')
query = query.filter(model.PackageRevision.current==True)
packages = query.all()
return [getattr(p, ref_package_by) for p in packages]
def current_package_list_with_resources(context, data_dict):
model = context["model"]
user = context["user"]
limit = data_dict.get("limit")
page = int(data_dict.get('page', 1))
check_access('current_package_list_with_resources', context, data_dict)
query = model.Session.query(model.PackageRevision)
query = query.filter(model.PackageRevision.state=='active')
query = query.filter(model.PackageRevision.current==True)
query = query.order_by(model.package_revision_table.c.revision_timestamp.desc())
if limit:
query = query.limit(int(limit))
query = query.offset((page-1)*limit)
pack_rev = query.all()
return _package_list_with_resources(context, pack_rev)
def revision_list(context, data_dict):
model = context['model']
check_access('revision_list', context, data_dict)
revs = model.Session.query(model.Revision).all()
return [rev.id for rev in revs]
def package_revision_list(context, data_dict):
model = context["model"]
id = data_dict["id"]
pkg = model.Package.get(id)
if pkg is None:
raise NotFound
check_access('package_revision_list',context, data_dict)
revision_dicts = []
for revision, object_revisions in pkg.all_related_revisions:
revision_dicts.append(model.revision_as_dict(revision,
include_packages=False,
include_groups=False))
return revision_dicts
def related_show(context, data_dict=None):
"""
Shows a single related item
context:
model - The CKAN model module
user - The name of the current user
data_dict:
id - The ID of the related item we want to show
"""
model = context['model']
id = data_dict['id']
related = model.Related.get(id)
context['related'] = related
if related is None:
raise NotFound
check_access('related_show',context, data_dict)
schema = context.get('schema') or ckan.logic.schema.default_related_schema()
related_dict = model_dictize.related_dictize(related, context)
related_dict, errors = validate(related_dict, schema, context=context)
return related_dict
def related_list(context, data_dict=None):
"""
List the related items which may be for a specific package which
should be mentioned in the data_dict
context:
model - The CKAN model module
user - The name of the current user
session - The current DB session
data_dict:
id - The ID of the dataset to which we want to list related items
or
dataset - The dataset (package) model
If neither value is in the data_dict then all related items will
be returned, and the ordering requested will be applied.
"""
model = context['model']
session = context['session']
dataset = data_dict.get('dataset', None)
if not dataset:
dataset = model.Package.get(data_dict.get('id'))
check_access('related_show',context, data_dict)
related_list = []
if not dataset:
related_list = model.Session.query(model.Related)
tfilter = data_dict.get('type_filter', None)
if tfilter:
related_list = related_list.filter(model.Related.type == tfilter)
else:
relateds = model.Related.get_for_dataset(dataset, status='active')
related_items = (r.related for r in relateds)
related_list = model_dictize.related_list_dictize( related_items, context)
return related_list
def member_list(context, data_dict=None):
"""
Returns a list of (id,type,capacity) tuples that are members of the
specified group if the user has permission to 'get' the group.
context:
model - The CKAN model module
user - The name of the current user
data_dict:
group - The ID of the group to which we want to list members
object_type - The optional name of the type being added, all lowercase,
e.g. package, or user
capacity - The optional capacity of objects that we want to retrieve
"""
model = context['model']
user = context['user']
group = context['group']
group_id = data_dict['group']
obj_type = data_dict.get('object_type', None)
capacity = data_dict.get('capacity', None)
# User must be able to update the group to remove a member from it
check_access('group_show', context, data_dict)
q = model.Session.query(model.Member).\
filter(model.Member.group_id == group.id).\
filter(model.Member.state == "active")
if obj_type:
q = q.filter(model.Member.table_name == obj_type)
if capacity:
q = q.filter(model.Member.capacity == capacity)
lookup = {}
def type_lookup(name):
if name in lookup:
return lookup[name]
if hasattr(model, name.title()):
lookup[name] = getattr(model,name.title())
return lookup[name]
return None
return [ (m.table_id, type_lookup(m.table_name) ,m.capacity,)
for m in q.all() ]
def group_list(context, data_dict):
'''Returns a list of groups'''
model = context['model']
user = context['user']
api = context.get('api_version')
ref_group_by = 'id' if api == 2 else 'name';
order_by = data_dict.get('order_by', 'name')
if order_by not in set(('name', 'packages')):
raise logic.ParameterError('"order_by" value %r not implemented.' % order_by)
all_fields = data_dict.get('all_fields',None)
check_access('group_list',context, data_dict)
query = model.Session.query(model.Group).join(model.GroupRevision)
query = query.filter(model.GroupRevision.state=='active')
query = query.filter(model.GroupRevision.current==True)
if order_by == 'name':
sort_by, reverse = 'name', False
groups = query.all()
if order_by == 'packages':
sort_by, reverse = 'packages', True
group_list = model_dictize.group_list_dictize(groups, context,
lambda x:x[sort_by], reverse)
if not all_fields:
group_list = [group[ref_group_by] for group in group_list]
return group_list
def group_list_authz(context, data_dict):
'''
Returns a list of groups which the user is allowed to edit
If 'available_only' is specified, the existing groups in the package are
removed.
'''
model = context['model']
user = context['user']
available_only = data_dict.get('available_only',False)
check_access('group_list_authz',context, data_dict)
query = Authorizer().authorized_query(user, model.Group, model.Action.EDIT)
groups = set(query.all())
if available_only:
package = context.get('package')
if package:
groups = groups - set(package.get_groups())
return [{'id':group.id,'name':group.name} for group in groups]
def group_revision_list(context, data_dict):
model = context['model']
id = data_dict['id']
group = model.Group.get(id)
if group is None:
raise NotFound
check_access('group_revision_list',context, data_dict)
revision_dicts = []
for revision, object_revisions in group.all_related_revisions:
revision_dicts.append(model.revision_as_dict(revision,
include_packages=False,
include_groups=False))
return revision_dicts
def licence_list(context, data_dict):
model = context["model"]
check_access('licence_list',context, data_dict)
license_register = model.Package.get_license_register()
licenses = license_register.values()
licences = [l.as_dict() for l in licenses]
return licences
def tag_list(context, data_dict):
'''Return a list of tag dictionaries.
If a query is provided in the data_dict with key 'query' or 'q', then only
tags whose names match the given query will be returned. Otherwise, all
tags will be returned.
By default only free tags (tags that don't belong to a vocabulary) are
returned. If a 'vocabulary_id' is provided in the data_dict then tags
belonging to the given vocabulary (id or name) will be returned instead.
'''
model = context['model']
vocab_id_or_name = data_dict.get('vocabulary_id')
query = data_dict.get('query') or data_dict.get('q')
if query:
query = query.strip()
all_fields = data_dict.get('all_fields', None)
check_access('tag_list', context, data_dict)
if query:
tags = _tag_search(context, data_dict)
else:
tags = model.Tag.all(vocab_id_or_name)
tag_list = []
if tags:
if all_fields:
for tag in tags:
result_dict = model_dictize.tag_dictize(tag, context)
tag_list.append(result_dict)
else:
tag_list.extend([tag.name for tag in tags])
return tag_list
def user_list(context, data_dict):
'''Lists the current users'''
model = context['model']
user = context['user']
check_access('user_list',context, data_dict)
q = data_dict.get('q','')
order_by = data_dict.get('order_by','name')
query = model.Session.query(
model.User,
model.User.name.label('name'),
model.User.fullname.label('fullname'),
model.User.about.label('about'),
model.User.about.label('email'),
model.User.created.label('created'),
select([func.count(model.Revision.id)], or_(
model.Revision.author==model.User.name,
model.Revision.author==model.User.openid
)
).label('number_of_edits'),
select([func.count(model.UserObjectRole.id)], and_(
model.UserObjectRole.user_id==model.User.id,
model.UserObjectRole.context=='Package',
model.UserObjectRole.role=='admin'
)
).label('number_administered_packages')
)
if q:
query = model.User.search(q, query)
if order_by == 'edits':
query = query.order_by(desc(
select([func.count(model.Revision.id)], or_(
model.Revision.author==model.User.name,
model.Revision.author==model.User.openid
))
))
else:
query = query.order_by(
case([(or_(model.User.fullname == None, model.User.fullname == ''),
model.User.name)],
else_=model.User.fullname)
)
## hack for pagination
if context.get('return_query'):
return query
users_list = []
for user in query.all():
result_dict = model_dictize.user_dictize(user[0], context)
del result_dict['apikey']
users_list.append(result_dict)
return users_list
def package_relationships_list(context, data_dict):
##TODO needs to work with dictization layer
model = context['model']
user = context['user']
api = context.get('api_version')
id = data_dict["id"]
id2 = data_dict.get("id2")
rel = data_dict.get("rel")
ref_package_by = 'id' if api == 2 else 'name';
pkg1 = model.Package.get(id)
pkg2 = None
if not pkg1:
raise NotFound('First package named in request was not found.')
if id2:
pkg2 = model.Package.get(id2)
if not pkg2:
raise NotFound('Second package named in address was not found.')
if rel == 'relationships':
rel = None
check_access('package_relationships_list',context, data_dict)
# TODO: How to handle this object level authz?
relationships = Authorizer().\
authorized_package_relationships(\
user, pkg1, pkg2, rel, model.Action.READ)
if rel and not relationships:
raise NotFound('Relationship "%s %s %s" not found.'
% (id, rel, id2))
relationship_dicts = [rel.as_dict(pkg1, ref_package_by=ref_package_by)
for rel in relationships]
return relationship_dicts
def package_show(context, data_dict):
model = context['model']
context['session'] = model.Session
name_or_id = data_dict.get("id") or data_dict['name_or_id']
pkg = model.Package.get(name_or_id)
if pkg is None:
raise NotFound
context['package'] = pkg
check_access('package_show', context, data_dict)
package_dict = model_dictize.package_dictize(pkg, context)
for item in plugins.PluginImplementations(plugins.IPackageController):
item.read(pkg)
package_plugin = lib_plugins.lookup_package_plugin(package_dict['type'])
try:
schema = package_plugin.db_to_form_schema_options({
'type':'show',
'api': 'api_version' in context,
'context': context })
except AttributeError:
schema = package_plugin.db_to_form_schema()
if schema and context.get('validate', True):
package_dict, errors = validate(package_dict, schema, context=context)
return package_dict
def resource_show(context, data_dict):
model = context['model']
id = data_dict['id']
resource = model.Resource.get(id)
context['resource'] = resource
if not resource:
raise NotFound
check_access('resource_show', context, data_dict)
return model_dictize.resource_dictize(resource, context)
def resource_status_show(context, data_dict):
model = context['model']
id = get_or_bust(data_dict, 'id')
check_access('resource_status_show', context, data_dict)
# needs to be text query as celery tables are not in our model
q = text("""select status, date_done, traceback, task_status.*
from task_status left join celery_taskmeta
on task_status.value = celery_taskmeta.task_id and key = 'celery_task_id'
where entity_id = :entity_id """)
result = model.Session.connection().execute(q, entity_id=id)
result_list = [table_dictize(row, context) for row in result]
return result_list
def revision_show(context, data_dict):
model = context['model']
api = context.get('api_version')
id = data_dict['id']
ref_package_by = 'id' if api == 2 else 'name'
rev = model.Session.query(model.Revision).get(id)
if rev is None:
raise NotFound
rev_dict = model.revision_as_dict(rev, include_packages=True,
ref_package_by=ref_package_by)
return rev_dict
def group_show(context, data_dict):
'''Shows group details'''
model = context['model']
id = data_dict['id']
group = model.Group.get(id)
context['group'] = group
if group is None:
raise NotFound
check_access('group_show',context, data_dict)
group_dict = model_dictize.group_dictize(group, context)
for item in plugins.PluginImplementations(plugins.IGroupController):
item.read(group)
group_plugin = lib_plugins.lookup_group_plugin(group_dict['type'])
try:
schema = group_plugin.db_to_form_schema_options({
'type':'show',
'api': 'api_version' in context,
'context': context })
except AttributeError:
schema = group_plugin.db_to_form_schema()
if schema:
package_dict, errors = validate(group_dict, schema, context=context)
return group_dict
def group_package_show(context, data_dict):
"""
Shows all packages belonging to a group.
"""
model = context["model"]
user = context["user"]
id = data_dict['id']
limit = data_dict.get("limit")
group = model.Group.get(id)
context['group'] = group
if group is None:
raise NotFound
check_access('group_show', context, data_dict)
query = model.Session.query(model.PackageRevision)\
.filter(model.PackageRevision.state=='active')\
.filter(model.PackageRevision.current==True)\
.join(model.Member, model.Member.table_id==model.PackageRevision.id)\
.join(model.Group, model.Group.id==model.Member.group_id)\
.filter_by(id=group.id)\
.order_by(model.PackageRevision.name)
if limit:
query = query.limit(limit)
if context.get('return_query'):
return query
result = []
for pkg_rev in query.all():
result.append(model_dictize.package_dictize(pkg_rev, context))
return result
def tag_show(context, data_dict):
'''Shows tag details'''
model = context['model']
id = data_dict['id']
tag = model.Tag.get(id)
context['tag'] = tag
if tag is None:
raise NotFound
check_access('tag_show',context, data_dict)
tag_dict = model_dictize.tag_dictize(tag,context)
extended_packages = []
for package in tag_dict['packages']:
pkg = model.Package.get(package['id'])
extended_packages.append(model_dictize.package_dictize(pkg,context))
tag_dict['packages'] = extended_packages
return tag_dict
def user_show(context, data_dict):
'''Shows user details'''
model = context['model']
user = context['user']
id = data_dict.get('id',None)
provided_user = data_dict.get('user_obj',None)
if id:
user_obj = model.User.get(id)
context['user_obj'] = user_obj
if user_obj is None:
raise NotFound
elif provided_user:
context['user_obj'] = user_obj = provided_user
else:
raise NotFound
check_access('user_show',context, data_dict)
user_dict = model_dictize.user_dictize(user_obj,context)
if not (Authorizer().is_sysadmin(unicode(user)) or user == user_obj.name):
# If not sysadmin or the same user, strip sensible info
del user_dict['apikey']
del user_dict['reset_key']
revisions_q = model.Session.query(model.Revision
).filter_by(author=user_obj.name)
revisions_list = []
for revision in revisions_q.limit(20).all():
revision_dict = revision_show(context,{'id':revision.id})
revision_dict['state'] = revision.state
revisions_list.append(revision_dict)
user_dict['activity'] = revisions_list
user_dict['datasets'] = []
dataset_q = model.Session.query(model.Package).join(model.PackageRole
).filter_by(user=user_obj, role=model.Role.ADMIN
).limit(50)
for dataset in dataset_q:
try:
dataset_dict = package_show(context, {'id': dataset.id})
except logic.NotAuthorized:
continue
user_dict['datasets'].append(dataset_dict)
return user_dict
def package_show_rest(context, data_dict):
check_access('package_show_rest',context, data_dict)
logic.get_action('package_show')(context, data_dict)
pkg = context['package']
package_dict = model_dictize.package_to_api(pkg, context)
return package_dict
def group_show_rest(context, data_dict):
check_access('group_show_rest',context, data_dict)
logic.get_action('group_show')(context, data_dict)
group = context['group']
group_dict = model_dictize.group_to_api(group, context)
return group_dict
def tag_show_rest(context, data_dict):
check_access('tag_show_rest',context, data_dict)
logic.get_action('tag_show')(context, data_dict)
tag = context['tag']
tag_dict = model_dictize.tag_to_api(tag, context)
return tag_dict
def package_autocomplete(context, data_dict):
'''Returns packages containing the provided string in either the name
or the title'''
model = context['model']
session = context['session']
user = context['user']
q = data_dict['q']
like_q = u"%s%%" % q
check_access('package_autocomplete', context, data_dict)
query = model.Session.query(model.PackageRevision)
query = query.filter(model.PackageRevision.state=='active')
query = query.filter(model.PackageRevision.current==True)
query = query.filter(or_(model.PackageRevision.name.ilike(like_q),
model.PackageRevision.title.ilike(like_q)))
query = query.limit(10)
q_lower = q.lower()
pkg_list = []
for package in query:
if package.name.startswith(q_lower):
match_field = 'name'
match_displayed = package.name
else:
match_field = 'title'
match_displayed = '%s (%s)' % (package.title, package.name)
result_dict = {'name':package.name, 'title':package.title,
'match_field':match_field, 'match_displayed':match_displayed}
pkg_list.append(result_dict)
return pkg_list
def format_autocomplete(context, data_dict):
'''Returns formats containing the provided string'''
model = context['model']
session = context['session']
user = context['user']
check_access('format_autocomplete', context, data_dict)
q = data_dict.get('q', None)
if not q:
return []
limit = data_dict.get('limit', 5)
like_q = u'%' + q + u'%'
query = session.query(model.ResourceRevision.format,
func.count(model.ResourceRevision.format).label('total'))\
.filter(and_(
model.ResourceRevision.state == 'active',
model.ResourceRevision.current == True
))\
.filter(model.ResourceRevision.format.ilike(like_q))\
.group_by(model.ResourceRevision.format)\
.order_by('total DESC')\
.limit(limit)
return [resource.format.lower() for resource in query]
def user_autocomplete(context, data_dict):
'''Returns users containing the provided string'''
model = context['model']
session = context['session']
user = context['user']
q = data_dict.get('q',None)
if not q:
return []
check_access('user_autocomplete', context, data_dict)
limit = data_dict.get('limit',20)
query = model.User.search(q).limit(limit)
user_list = []
for user in query.all():
result_dict = {}
for k in ['id', 'name', 'fullname']:
result_dict[k] = getattr(user,k)
user_list.append(result_dict)
return user_list
def package_search(context, data_dict):
model = context['model']
session = context['session']
user = context['user']
check_access('package_search', context, data_dict)
# check if some extension needs to modify the search params
for item in plugins.PluginImplementations(plugins.IPackageController):
data_dict = item.before_search(data_dict)
# the extension may have decided that it is not necessary to perform
# the query
abort = data_dict.get('abort_search',False)
results = []
if not abort:
# return a list of package ids
data_dict['fl'] = 'id'
query = search.query_for(model.Package)
query.run(data_dict)
for package in query.results:
# get the package object
pkg_query = session.query(model.PackageRevision)\
.filter(model.PackageRevision.id == package)\
.filter(and_(
model.PackageRevision.state == u'active',
model.PackageRevision.current == True
))
pkg = pkg_query.first()
## if the index has got a package that is not in ckan then
## ignore it.
if not pkg:
log.warning('package %s in index but not in database' % package)
continue
result_dict = model_dictize.package_dictize(pkg,context)
results.append(result_dict)
count = query.count
facets = query.facets
else:
count = 0
facets = {}
results = []
search_results = {
'count': count,
'facets': facets,
'results': results
}
# Transform facets into a more useful data structure.
restructured_facets = {}
for key, value in search_results['facets'].items():
restructured_facets[key] = {
'title': key,
'items': []
}
for key_, value_ in value.items():
new_facet_dict = {}
new_facet_dict['name'] = key_
if key == 'groups':
group = model.Group.get(key_)
if group:
new_facet_dict['display_name'] = group.display_name
else:
new_facet_dict['display_name'] = key_
else:
new_facet_dict['display_name'] = key_
new_facet_dict['count'] = value_
restructured_facets[key]['items'].append(new_facet_dict)
search_results['search_facets'] = restructured_facets
# check if some extension needs to modify the search results
for item in plugins.PluginImplementations(plugins.IPackageController):
search_results = item.after_search(search_results,data_dict)
# After extensions have had a chance to modify the facets, sort them by
# display name.
for facet in search_results['search_facets']:
search_results['search_facets'][facet]['items'] = sorted(
search_results['search_facets'][facet]['items'],
key=lambda facet: facet['display_name'], reverse=True)
return search_results
def resource_search(context, data_dict):
model = context['model']
session = context['session']
fields = data_dict['fields']
order_by = data_dict.get('order_by')
offset = data_dict.get('offset')
limit = data_dict.get('limit')
# TODO: should we check for user authentication first?
q = model.Session.query(model.Resource)
resource_fields = model.Resource.get_columns()
for field, terms in fields.items():
if isinstance(terms, basestring):
terms = terms.split()
if field not in resource_fields:
raise search.SearchError('Field "%s" not recognised in Resource search.' % field)
for term in terms:
model_attr = getattr(model.Resource, field)
if field == 'hash':
q = q.filter(model_attr.ilike(unicode(term) + '%'))
elif field in model.Resource.get_extra_columns():
model_attr = getattr(model.Resource, 'extras')
like = or_(
model_attr.ilike(u'''%%"%s": "%%%s%%",%%''' % (field, term)),
model_attr.ilike(u'''%%"%s": "%%%s%%"}''' % (field, term))
)
q = q.filter(like)
else:
q = q.filter(model_attr.ilike('%' + unicode(term) + '%'))
if order_by is not None:
if hasattr(model.Resource, order_by):
q = q.order_by(getattr(model.Resource, order_by))
count = q.count()
q = q.offset(offset)
q = q.limit(limit)
results = []
for result in q:
if isinstance(result, tuple) and isinstance(result[0], model.DomainObject):
# This is the case for order_by rank due to the add_column.
results.append(result[0])
else:
results.append(result)
return {'count': count, 'results': results}
def _tag_search(context, data_dict):
'''Return a list of tag objects that contain the given string.
The query string should be provided in the data_dict with key 'query' or
'q'.
By default only free tags (tags that don't belong to a vocabulary) are
searched. If a 'vocabulary_id' is provided in the data_dict then tags
belonging to the given vocabulary (id or name) will be searched instead.
'''
model = context['model']
query = data_dict.get('query') or data_dict.get('q')
if query:
query = query.strip()
terms = [query] if query else []
fields = data_dict.get('fields', {})
offset = data_dict.get('offset')
limit = data_dict.get('limit')
# TODO: should we check for user authentication first?
q = model.Session.query(model.Tag)
if data_dict.has_key('vocabulary_id'):
# Filter by vocabulary.
vocab = model.Vocabulary.get(data_dict['vocabulary_id'])
if not vocab:
raise NotFound
q = q.filter(model.Tag.vocabulary_id == vocab.id)
else:
# If no vocabulary_name in data dict then show free tags only.
q = q.filter(model.Tag.vocabulary_id == None)
# If we're searching free tags, limit results to tags that are
# currently applied to a package.
q = q.distinct().join(model.Tag.package_tags)
for field, value in fields.items():
if field in ('tag', 'tags'):
terms.append(value)
if not len(terms):
return []
for term in terms:
escaped_term = misc.escape_sql_like_special_characters(term, escape='\\')
q = q.filter(model.Tag.name.ilike('%' + escaped_term + '%'))
q = q.offset(offset)
q = q.limit(limit)
return q.all()
def tag_search(context, data_dict):
'''Return a list of tag dictionaries that contain the given string.
The query string should be provided in the data_dict with key 'query' or
'q'.
By default only free tags (tags that don't belong to a vocabulary) are
searched. If a 'vocabulary_id' is provided in the data_dict then tags
belonging to the given vocabulary (id or name) will be searched instead.
Returns a dictionary with keys 'count' (the number of tags in the result)
and 'results' (the list of tag dicts).
'''
tags = _tag_search(context, data_dict)
return {'count': len(tags),
'results': [table_dictize(tag, context) for tag in tags]}