-
Notifications
You must be signed in to change notification settings - Fork 2k
/
get.py
2293 lines (1768 loc) · 76.1 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
import json
from pylons import config
from pylons.i18n import _
import webhelpers.html
import sqlalchemy
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
# Ensure they are module-private so that they don't get loaded as available
# actions in the action API.
_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
_select = sqlalchemy.sql.select
_aliased = sqlalchemy.orm.aliased
_or_ = sqlalchemy.or_
_and_ = sqlalchemy.and_
_func = sqlalchemy.func
_desc = sqlalchemy.desc
_case = sqlalchemy.case
_text = sqlalchemy.text
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):
'''Return ``True``.
:rtype: boolean
'''
_check_access('site_read',context,data_dict)
return True
def package_list(context, data_dict):
'''Return a list of the names of the site's datasets (packages).
:rtype: list of strings
'''
model = context["model"]
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):
'''Return a list of the site's datasets (packages) and their resources.
The list is sorted most-recently-modified first.
:param limit: if given, the list of datasets will be broken into pages of
at most ``limit`` datasets per page and only one page will be returned
at a time (optional)
:type limit: int
:param page: when ``limit`` is given, which page to return
:type page: int
:rtype: list of dictionaries
'''
model = context["model"]
if data_dict.has_key('limit'):
try:
limit = int(data_dict['limit'])
if limit < 0:
limit = 0
except ValueError, e:
raise logic.ParameterError("'limit' should be an int")
else:
limit = None
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 is not None:
query = query.limit(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):
'''Return a list of the IDs of the site's revisions.
:rtype: list of strings
'''
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):
'''Return a dataset (package)'s revisions as a list of dictionaries.
:param id: the id or name of the dataset
:type id: string
'''
model = context["model"]
id = _get_or_bust(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):
'''Return a single related item.
:param id: the id of the related item to show
:type id: string
:rtype: dictionary
'''
model = context['model']
id = _get_or_bust(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):
'''Return a dataset's related items.
Either the ``id`` or the ``dataset`` parameter must be given.
:param id: id or name of the dataset (optional)
:type id: string
:param dataset: dataset dictionary of the dataset (optional)
:type dataset: dictionary
:rtype: list of dictionaries
'''
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)
filter_on_type = data_dict.get('type_filter', None)
if filter_on_type:
related_list = related_list.filter(model.Related.type == filter_on_type)
sort = data_dict.get('sort', None)
if sort:
sortables = {
'view_count_asc' : model.Related.view_count.asc,
'view_count_desc': model.Related.view_count.desc,
'created_asc' : model.Related.created.asc,
'created_desc': model.Related.created.desc,
}
s = sortables.get(sort, None)
if s:
related_list = related_list.order_by( s() )
if data_dict.get('featured', False):
related_list = related_list.filter(model.Related.featured == 1)
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):
'''Return the members of a group.
The user must have permission to 'get' the group.
:param id: the id or name of the group
:type id: string
:param object_type: restrict the members returned to those of a given type,
e.g. ``'user'`` or ``'package'`` (optional, default: ``None``)
:type object_type: string
:param capacity: restrict the members returned to those with a given
capacity, e.g. ``'member'``, ``'editor'``, ``'admin'``, ``'public'``,
``'private'`` (optional, default: ``None``)
:type capacity: string
:rtype: list of (id, type, capacity) tuples
'''
model = context['model']
user = context['user']
group = model.Group.get(_get_or_bust(data_dict, 'id'))
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):
'''Return a list of the names of the site's groups.
:param order_by: the field to sort the list by, must be ``'name'`` or
``'packages'`` (optional, default: ``'name'``) Deprecated use sort.
:type order_by: string
:param sort: sorting of the search results. Optional. Default:
"name asc" string of field name and sort-order. The allowed fields are
'name' and 'packages'
:type sort: string
:param groups: a list of names of the groups to return, if given only
groups whose names are in this list will be returned (optional)
:type groups: list of strings
:param all_fields: return full group dictionaries instead of just names
(optional, default: ``False``)
:type all_fields: boolean
:rtype: list of strings
'''
model = context['model']
api = context.get('api_version')
groups = data_dict.get('groups')
ref_group_by = 'id' if api == 2 else 'name';
sort = data_dict.get('sort', 'name')
# order_by deprecated in ckan 1.8
# if it is supplied and sort isn't use order_by and raise a warning
order_by = data_dict.get('order_by')
if order_by:
log.warn('`order_by` deprecated please use `sort`')
if not data_dict.get('sort'):
sort = order_by
# if the sort is packages and no sort direction is supplied we want to do a
# reverse sort to maintain compatibility.
if sort.strip() == 'packages':
sort = 'packages desc'
sort_info = _unpick_search(sort,
allowed_fields=['name', 'packages'],
total=1)
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 groups:
query = query.filter(model.GroupRevision.name.in_(groups))
groups = query.all()
group_list = model_dictize.group_list_dictize(groups, context,
lambda x:x[sort_info[0][0]],
sort_info[0][1] == 'desc')
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):
'''Return the list of groups that the user is authorized to edit.
:param available_only: remove the existing groups in the package
(optional, default: ``False``)
:type available_only: boolean
:returns: the names of groups that the user is authorized to edit
:rtype: list of strings
'''
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):
'''Return a group's revisions.
:param id: the name or id of the group
:type id: string
:rtype: list of dictionaries
'''
model = context['model']
id = _get_or_bust(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):
'''Return the list of licenses available for datasets on the site.
:rtype: list of dictionaries
'''
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 the site's tags.
By default only free tags (tags that don't belong to a vocabulary) are
returned. If the ``vocabulary_id`` argument is given then only tags
belonging to that vocabulary will be returned instead.
:param query: a tag name query to search for, if given only tags whose
names contain this string will be returned (optional)
:type query: string
:param vocabulary_id: the id or name of a vocabulary, if give only tags
that belong to this vocabulary will be returned (optional)
:type vocabulary_id: string
:param all_fields: return full tag dictionaries instead of just names
(optional, default: ``False``)
:type all_fields: boolean
:rtype: list of dictionaries
'''
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, count = _tag_search(context, data_dict)
else:
tags = model.Tag.all(vocab_id_or_name)
if tags:
if all_fields:
tag_list = model_dictize.tag_list_dictize(tags, context)
else:
tag_list = [tag.name for tag in tags]
else:
tag_list = []
return tag_list
def user_list(context, data_dict):
'''Return a list of the site's user accounts.
:param q: restrict the users returned to those whose names contain a string
(optional)
:type q: string
:param order_by: which field to sort the list by (optional, default:
``'name'``)
:type order_by: string
:rtype: list of dictionaries
'''
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):
'''Return a dataset (package)'s relationships.
:param id: the id or name of the package
:type id: string
:param id2:
:type id2:
:param rel:
:type rel:
:rtype: list of dictionaries
'''
##TODO needs to work with dictization layer
model = context['model']
user = context['user']
api = context.get('api_version')
id = _get_or_bust(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):
'''Return the metadata of a dataset (package) and its resources.
:param id: the id or name of the dataset
:type id: string
:rtype: dictionary
'''
model = context['model']
context['session'] = model.Session
name_or_id = data_dict.get("id") or _get_or_bust(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):
'''Return the metadata of a resource.
:param id: the id of the resource
:type id: string
:rtype: dictionary
'''
model = context['model']
id = _get_or_bust(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):
'''Return the statuses of a resource's tasks.
:param id: the id of the resource
:type id: string
:rtype: list of (status, date_done, traceback, task_status) dictionaries
'''
try:
import ckan.lib.celery_app as celery_app
except ImportError:
return {'message': 'queue is not installed on this instance'}
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):
'''Return the details of a revision.
:param id: the id of the revision
:type id: string
:rtype: dictionary
'''
model = context['model']
api = context.get('api_version')
id = _get_or_bust(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):
'''Return the details of a group.
:param id: the id or name of the group
:type id: string
:rtype: dictionary
'''
model = context['model']
id = _get_or_bust(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:
group_dict, errors = _validate(group_dict, schema, context=context)
return group_dict
def group_package_show(context, data_dict):
'''Return the datasets (packages) of a group.
:param id: the id or name of the group
:type id: string
:param limit: the maximum number of datasets to return (optional)
:type limit: int
:rtype: list of dictionaries
'''
model = context["model"]
user = context["user"]
id = _get_or_bust(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):
'''Return the details of a tag and all its datasets.
:param id: the name or id of the tag
:type id: string
:returns: the details of the tag, including a list of all of the tag's
datasets and their details
:rtype: dictionary
'''
model = context['model']
id = _get_or_bust(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):
'''Return a user account.
Either the ``id`` or the ``user_obj`` parameter must be given.
:param id: the id or name of the user (optional)
:type id: string
:param user_obj: the user dictionary of the user (optional)
:type user_obj: user dictionary
:rtype: dictionary
'''
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):
'''Return a list of datasets (packages) that match a string.
Datasets with names or titles that contain the query string will be
returned.
:param q: the string to search for
:type q: string
:rtype: list of dictionaries
'''
model = context['model']
session = context['session']
user = context['user']
q = _get_or_bust(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):
'''Return a list of resource formats whose names contain a string.
:param q: the string to search for
:type q: string
:param limit: the maximum number of resource formats to return (optional,
default: 5)
:type limit: int
:rtype: list of strings
'''
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):
'''Return a list of user names that contain a string.
:param q: the string to search for
:type q: string
:param limit: the maximum number of user names to return (optional,
default: 20)
:type limit: int
:rtype: a list of user dictionaries each with keys ``'name'``,
``'fullname'``, and ``'id'``
'''
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)