-
Notifications
You must be signed in to change notification settings - Fork 2k
/
update.py
1240 lines (949 loc) · 39.4 KB
/
update.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
'''API functions for updating existing data in CKAN.'''
import logging
import datetime
import json
from pylons import config
from vdm.sqlalchemy.base import SQLAlchemySession
import paste.deploy.converters as converters
import ckan.plugins as plugins
import ckan.logic as logic
import ckan.logic.schema as schema_
import ckan.lib.dictization as dictization
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.lib.dictization.model_save as model_save
import ckan.lib.navl.dictization_functions
import ckan.lib.navl.validators as validators
import ckan.lib.plugins as lib_plugins
import ckan.lib.email_notifications as email_notifications
import ckan.lib.search as search
import ckan.lib.uploader as uploader
from ckan.common import _, request
log = logging.getLogger(__name__)
# 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
_get_action = logic.get_action
_check_access = logic.check_access
NotFound = logic.NotFound
ValidationError = logic.ValidationError
_get_or_bust = logic.get_or_bust
def _make_latest_rev_active(context, q):
session = context['model'].Session
old_current = q.filter_by(current=True).first()
if old_current:
old_current.current = False
session.add(old_current)
latest_rev = q.filter_by(expired_timestamp=datetime.datetime(9999, 12, 31)).one()
latest_rev.current = True
if latest_rev.state in ('pending-deleted', 'deleted'):
latest_rev.state = 'deleted'
latest_rev.continuity.state = 'deleted'
else:
latest_rev.continuity.state = 'active'
latest_rev.state = 'active'
session.add(latest_rev)
##this is just a way to get the latest revision that changed
##in order to timestamp
old_latest = context.get('latest_revision_date')
if old_latest:
if latest_rev.revision_timestamp > old_latest:
context['latest_revision_date'] = latest_rev.revision_timestamp
context['latest_revision'] = latest_rev.revision_id
else:
context['latest_revision_date'] = latest_rev.revision_timestamp
context['latest_revision'] = latest_rev.revision_id
def make_latest_pending_package_active(context, data_dict):
'''
.. todo:: What does this function do?
You must be authorized to update the dataset.
:param id: the name or id of the dataset, e.g. ``'warandpeace'``
:type id: string
'''
model = context['model']
session = model.Session
SQLAlchemySession.setattr(session, 'revisioning_disabled', True)
id = _get_or_bust(data_dict, "id")
pkg = model.Package.get(id)
_check_access('make_latest_pending_package_active', context, data_dict)
#packages
q = session.query(model.PackageRevision).filter_by(id=pkg.id)
_make_latest_rev_active(context, q)
#resources
for resource in pkg.resources_all:
q = session.query(model.ResourceRevision).filter_by(id=resource.id)
_make_latest_rev_active(context, q)
#tags
for tag in pkg.package_tag_all:
q = session.query(model.PackageTagRevision).filter_by(id=tag.id)
_make_latest_rev_active(context, q)
#extras
for extra in pkg.extras_list:
q = session.query(model.PackageExtraRevision).filter_by(id=extra.id)
_make_latest_rev_active(context, q)
latest_revision = context.get('latest_revision')
if not latest_revision:
return
q = session.query(model.Revision).filter_by(id=latest_revision)
revision = q.first()
revision.approved_timestamp = datetime.datetime.now()
session.add(revision)
if not context.get('defer_commit'):
session.commit()
def related_update(context, data_dict):
'''Update a related item.
You must be the owner of a related item to update it.
For further parameters see
:py:func:`~ckan.logic.action.create.related_create`.
:param id: the id of the related item to update
:type id: string
:returns: the updated related item
:rtype: dictionary
'''
model = context['model']
id = _get_or_bust(data_dict, "id")
session = context['session']
schema = context.get('schema') or schema_.default_update_related_schema()
related = model.Related.get(id)
context["related"] = related
if not related:
logging.error('Could not find related ' + id)
raise NotFound(_('Item was not found.'))
_check_access('related_update', context, data_dict)
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
related = model_save.related_dict_save(data, context)
dataset_dict = None
if 'package' in context:
dataset = context['package']
dataset_dict = ckan.lib.dictization.table_dictize(dataset, context)
related_dict = model_dictize.related_dictize(related, context)
activity_dict = {
'user_id': context['user'],
'object_id': related.id,
'activity_type': 'changed related item',
}
activity_dict['data'] = {
'related': related_dict,
'dataset': dataset_dict,
}
activity_create_context = {
'model': model,
'user': context['user'],
'defer_commit': True,
'ignore_auth': True,
'session': session
}
_get_action('activity_create')(activity_create_context, activity_dict)
if not context.get('defer_commit'):
model.repo.commit()
return model_dictize.related_dictize(related, context)
def resource_update(context, data_dict):
'''Update a resource.
To update a resource you must be authorized to update the dataset that the
resource belongs to.
For further parameters see
:py:func:`~ckan.logic.action.create.resource_create`.
:param id: the id of the resource to update
:type id: string
:returns: the updated resource
:rtype: string
'''
model = context['model']
user = context['user']
id = _get_or_bust(data_dict, "id")
resource = model.Resource.get(id)
context["resource"] = resource
if not resource:
logging.error('Could not find resource ' + id)
raise NotFound(_('Resource was not found.'))
_check_access('resource_update', context, data_dict)
del context["resource"]
package_id = resource.package.id
pkg_dict = _get_action('package_show')(context, {'id': package_id})
for n, p in enumerate(pkg_dict['resources']):
if p['id'] == id:
break
else:
logging.error('Could not find resource ' + id)
raise NotFound(_('Resource was not found.'))
upload = uploader.ResourceUpload(data_dict)
pkg_dict['resources'][n] = data_dict
try:
context['defer_commit'] = True
context['use_cache'] = False
pkg_dict = _get_action('package_update')(context, pkg_dict)
context.pop('defer_commit')
except ValidationError, e:
errors = e.error_dict['resources'][n]
raise ValidationError(errors)
upload.upload(id, uploader.get_max_resource_size())
model.repo.commit()
return _get_action('resource_show')(context, {'id': id})
def package_update(context, data_dict):
'''Update a dataset (package).
You must be authorized to edit the dataset and the groups that it belongs
to.
It is recommended to call
:py:func:`ckan.logic.action.get.package_show`, make the desired changes to
the result, and then call ``package_update()`` with it.
Plugins may change the parameters of this function depending on the value
of the dataset's ``type`` attribute, see the
:py:class:`~ckan.plugins.interfaces.IDatasetForm` plugin interface.
For further parameters see
:py:func:`~ckan.logic.action.create.package_create`.
:param id: the name or id of the dataset to update
:type id: string
:returns: the updated dataset (if ``'return_package_dict'`` is ``True`` in
the context, which is the default. Otherwise returns just the
dataset id)
:rtype: dictionary
'''
model = context['model']
user = context['user']
name_or_id = data_dict.get("id") or data_dict['name']
pkg = model.Package.get(name_or_id)
if pkg is None:
raise NotFound(_('Package was not found.'))
context["package"] = pkg
data_dict["id"] = pkg.id
_check_access('package_update', context, data_dict)
# get the schema
package_plugin = lib_plugins.lookup_package_plugin(pkg.type)
if 'schema' in context:
schema = context['schema']
else:
schema = package_plugin.update_package_schema()
if 'api_version' not in context:
# check_data_dict() is deprecated. If the package_plugin has a
# check_data_dict() we'll call it, if it doesn't have the method we'll
# do nothing.
check_data_dict = getattr(package_plugin, 'check_data_dict', None)
if check_data_dict:
try:
package_plugin.check_data_dict(data_dict, schema)
except TypeError:
# Old plugins do not support passing the schema so we need
# to ensure they still work.
package_plugin.check_data_dict(data_dict)
data, errors = _validate(data_dict, schema, context)
log.debug('package_update validate_errs=%r user=%s package=%s data=%r',
errors, context.get('user'),
context.get('package').name if context.get('package') else '',
data)
if errors:
model.Session.rollback()
raise ValidationError(errors)
rev = model.repo.new_revision()
rev.author = user
if 'message' in context:
rev.message = context['message']
else:
rev.message = _(u'REST API: Update object %s') % data.get("name")
#avoid revisioning by updating directly
model.Session.query(model.Package).filter_by(id=pkg.id).update(
{"metadata_modified": datetime.datetime.utcnow()})
model.Session.refresh(pkg)
pkg = model_save.package_dict_save(data, context)
context_org_update = context.copy()
context_org_update['ignore_auth'] = True
context_org_update['defer_commit'] = True
_get_action('package_owner_org_update')(context_org_update,
{'id': pkg.id,
'organization_id': pkg.owner_org})
for item in plugins.PluginImplementations(plugins.IPackageController):
item.edit(pkg)
item.after_update(context, data)
if not context.get('defer_commit'):
model.repo.commit()
log.debug('Updated object %s' % pkg.name)
return_id_only = context.get('return_id_only', False)
# Make sure that a user provided schema is not used on package_show
context.pop('schema', None)
# we could update the dataset so we should still be able to read it.
context['ignore_auth'] = True
output = data_dict['id'] if return_id_only \
else _get_action('package_show')(context, {'id': data_dict['id']})
return output
def package_resource_reorder(context, data_dict):
'''Reorder resources against datasets. If only partial resource ids are
supplied then these are assumed to be first and the other resources will
stay in their original order
:param id: the id or name of the package to update
:type id: string
:param order: a list of resource ids in the order needed
:type list: list
'''
id = _get_or_bust(data_dict, "id")
order = _get_or_bust(data_dict, "order")
if not isinstance(order, list):
raise ValidationError({'order': 'Must be a list of resource'})
if len(set(order)) != len(order):
raise ValidationError({'order': 'Must supply unique resource_ids'})
package_dict = _get_action('package_show')(context, {'id': id})
existing_resources = package_dict.get('resources', [])
ordered_resources = []
for resource_id in order:
for i in range(0, len(existing_resources)):
if existing_resources[i]['id'] == resource_id:
resource = existing_resources.pop(i)
ordered_resources.append(resource)
break
else:
raise ValidationError(
{'order':
'resource_id {id} can not be found'.format(id=resource_id)}
)
new_resources = ordered_resources + existing_resources
package_dict['resources'] = new_resources
_check_access('package_resource_reorder', context, package_dict)
_get_action('package_update')(context, package_dict)
return {'id': id, 'order': [resource['id'] for resource in new_resources]}
def _update_package_relationship(relationship, comment, context):
model = context['model']
api = context.get('api_version')
ref_package_by = 'id' if api == 2 else 'name'
is_changed = relationship.comment != comment
if is_changed:
rev = model.repo.new_revision()
rev.author = context["user"]
rev.message = (_(u'REST API: Update package relationship: %s %s %s') %
(relationship.subject, relationship.type, relationship.object))
relationship.comment = comment
if not context.get('defer_commit'):
model.repo.commit_and_remove()
rel_dict = relationship.as_dict(package=relationship.subject,
ref_package_by=ref_package_by)
return rel_dict
def package_relationship_update(context, data_dict):
'''Update a relationship between two datasets (packages).
You must be authorized to edit both the subject and the object datasets.
:param id: the id of the package relationship to update
:type id: string
:param subject: the name or id of the dataset that is the subject of the
relationship (optional)
:type subject: string
:param object: the name or id of the dataset that is the object of the
relationship (optional)
:param type: the type of the relationship, one of ``'depends_on'``,
``'dependency_of'``, ``'derives_from'``, ``'has_derivation'``,
``'links_to'``, ``'linked_from'``, ``'child_of'`` or ``'parent_of'``
(optional)
:type type: string
:param comment: a comment about the relationship (optional)
:type comment: string
:returns: the updated relationship
:rtype: dictionary
'''
model = context['model']
schema = context.get('schema') or schema_.default_update_relationship_schema()
id, id2, rel = _get_or_bust(data_dict, ['subject', 'object', 'type'])
pkg1 = model.Package.get(id)
pkg2 = model.Package.get(id2)
if not pkg1:
raise NotFound('Subject package %r was not found.' % id)
if not pkg2:
return NotFound('Object package %r was not found.' % id2)
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
_check_access('package_relationship_update', context, data_dict)
existing_rels = pkg1.get_relationships_with(pkg2, rel)
if not existing_rels:
raise NotFound('This relationship between the packages was not found.')
entity = existing_rels[0]
comment = data_dict.get('comment', u'')
context['relationship'] = entity
return _update_package_relationship(entity, comment, context)
def _group_or_org_update(context, data_dict, is_org=False):
model = context['model']
user = context['user']
session = context['session']
id = _get_or_bust(data_dict, 'id')
group = model.Group.get(id)
context["group"] = group
if group is None:
raise NotFound('Group was not found.')
# get the schema
group_plugin = lib_plugins.lookup_group_plugin(group.type)
try:
schema = group_plugin.form_to_db_schema_options({'type':'update',
'api':'api_version' in context,
'context': context})
except AttributeError:
schema = group_plugin.form_to_db_schema()
upload = uploader.Upload('group', group.image_url)
upload.update_data_dict(data_dict, 'image_url',
'image_upload', 'clear_upload')
if is_org:
_check_access('organization_update', context, data_dict)
else:
_check_access('group_update', context, data_dict)
if 'api_version' not in context:
# old plugins do not support passing the schema so we need
# to ensure they still work
try:
group_plugin.check_data_dict(data_dict, schema)
except TypeError:
group_plugin.check_data_dict(data_dict)
data, errors = _validate(data_dict, schema, context)
log.debug('group_update validate_errs=%r user=%s group=%s data_dict=%r',
errors, context.get('user'),
context.get('group').name if context.get('group') else '',
data_dict)
if errors:
session.rollback()
raise ValidationError(errors)
rev = model.repo.new_revision()
rev.author = user
if 'message' in context:
rev.message = context['message']
else:
rev.message = _(u'REST API: Update object %s') % data.get("name")
# when editing an org we do not want to update the packages if using the
# new templates.
if ((not is_org)
and not converters.asbool(
config.get('ckan.legacy_templates', False))
and 'api_version' not in context):
context['prevent_packages_update'] = True
group = model_save.group_dict_save(data, context)
if is_org:
plugin_type = plugins.IOrganizationController
else:
plugin_type = plugins.IGroupController
for item in plugins.PluginImplementations(plugin_type):
item.edit(group)
if is_org:
activity_type = 'changed organization'
else:
activity_type = 'changed group'
activity_dict = {
'user_id': model.User.by_name(user.decode('utf8')).id,
'object_id': group.id,
'activity_type': activity_type,
}
# Handle 'deleted' groups.
# When the user marks a group as deleted this comes through here as
# a 'changed' group activity. We detect this and change it to a 'deleted'
# activity.
if group.state == u'deleted':
if session.query(ckan.model.Activity).filter_by(
object_id=group.id, activity_type='deleted').all():
# A 'deleted group' activity for this group has already been
# emitted.
# FIXME: What if the group was deleted and then activated again?
activity_dict = None
else:
# We will emit a 'deleted group' activity.
activity_dict['activity_type'] = 'deleted group'
if activity_dict is not None:
activity_dict['data'] = {
'group': dictization.table_dictize(group, context)
}
activity_create_context = {
'model': model,
'user': user,
'defer_commit': True,
'ignore_auth': True,
'session': session
}
_get_action('activity_create')(activity_create_context, activity_dict)
# TODO: Also create an activity detail recording what exactly changed
# in the group.
upload.upload(uploader.get_max_image_size())
if not context.get('defer_commit'):
model.repo.commit()
return model_dictize.group_dictize(group, context)
def group_update(context, data_dict):
'''Update a group.
You must be authorized to edit the group.
Plugins may change the parameters of this function depending on the value
of the group's ``type`` attribute, see the
:py:class:`~ckan.plugins.interfaces.IGroupForm` plugin interface.
For further parameters see
:py:func:`~ckan.logic.action.create.group_create`.
:param id: the name or id of the group to update
:type id: string
:returns: the updated group
:rtype: dictionary
'''
return _group_or_org_update(context, data_dict)
def organization_update(context, data_dict):
'''Update a organization.
You must be authorized to edit the organization.
For further parameters see
:py:func:`~ckan.logic.action.create.organization_create`.
:param id: the name or id of the organization to update
:type id: string
:returns: the updated organization
:rtype: dictionary
'''
return _group_or_org_update(context, data_dict, is_org=True)
def user_update(context, data_dict):
'''Update a user account.
Normal users can only update their own user accounts. Sysadmins can update
any user account.
For further parameters see
:py:func:`~ckan.logic.action.create.user_create`.
:param id: the name or id of the user to update
:type id: string
:returns: the updated user account
:rtype: dictionary
'''
model = context['model']
user = context['user']
session = context['session']
schema = context.get('schema') or schema_.default_update_user_schema()
id = _get_or_bust(data_dict, 'id')
user_obj = model.User.get(id)
context['user_obj'] = user_obj
if user_obj is None:
raise NotFound('User was not found.')
_check_access('user_update', context, data_dict)
data, errors = _validate(data_dict, schema, context)
if errors:
session.rollback()
raise ValidationError(errors)
user = model_save.user_dict_save(data, context)
activity_dict = {
'user_id': user.id,
'object_id': user.id,
'activity_type': 'changed user',
}
activity_create_context = {
'model': model,
'user': user,
'defer_commit': True,
'ignore_auth': True,
'session': session
}
_get_action('activity_create')(activity_create_context, activity_dict)
# TODO: Also create an activity detail recording what exactly changed in
# the user.
if not context.get('defer_commit'):
model.repo.commit()
return model_dictize.user_dictize(user, context)
def task_status_update(context, data_dict):
'''Update a task status.
:param id: the id of the task status to update
:type id: string
:param entity_id:
:type entity_id: string
:param entity_type:
:type entity_type: string
:param task_type:
:type task_type: string
:param key:
:type key: string
:param value: (optional)
:type value:
:param state: (optional)
:type state:
:param last_updated: (optional)
:type last_updated:
:param error: (optional)
:type error:
:returns: the updated task status
:rtype: dictionary
'''
model = context['model']
session = model.meta.create_local_session()
context['session'] = session
user = context['user']
id = data_dict.get("id")
schema = context.get('schema') or schema_.default_task_status_schema()
if id:
task_status = model.TaskStatus.get(id)
context["task_status"] = task_status
if task_status is None:
raise NotFound(_('TaskStatus was not found.'))
_check_access('task_status_update', context, data_dict)
data, errors = _validate(data_dict, schema, context)
if errors:
session.rollback()
raise ValidationError(errors)
task_status = model_save.task_status_dict_save(data, context)
session.commit()
session.close()
return model_dictize.task_status_dictize(task_status, context)
def task_status_update_many(context, data_dict):
'''Update many task statuses at once.
:param data: the task_status dictionaries to update, for the format of task
status dictionaries see
:py:func:`~task_status_update`
:type data: list of dictionaries
:returns: the updated task statuses
:rtype: list of dictionaries
'''
results = []
model = context['model']
deferred = context.get('defer_commit')
context['defer_commit'] = True
for data in data_dict['data']:
results.append(_get_action('task_status_update')(context, data))
if not deferred:
context.pop('defer_commit')
if not context.get('defer_commit'):
model.Session.commit()
return {'results': results}
def term_translation_update(context, data_dict):
'''Create or update a term translation.
You must be a sysadmin to create or update term translations.
:param term: the term to be translated, in the original language, e.g.
``'romantic novel'``
:type term: string
:param term_translation: the translation of the term, e.g.
``'Liebesroman'``
:type term_translation: string
:param lang_code: the language code of the translation, e.g. ``'de'``
:type lang_code: string
:returns: the newly created or updated term translation
:rtype: dictionary
'''
model = context['model']
_check_access('term_translation_update', context, data_dict)
schema = {'term': [validators.not_empty, unicode],
'term_translation': [validators.not_empty, unicode],
'lang_code': [validators.not_empty, unicode]}
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
trans_table = model.term_translation_table
update = trans_table.update()
update = update.where(trans_table.c.term == data['term'])
update = update.where(trans_table.c.lang_code == data['lang_code'])
update = update.values(term_translation = data['term_translation'])
conn = model.Session.connection()
result = conn.execute(update)
# insert if not updated
if not result.rowcount:
conn.execute(trans_table.insert().values(**data))
if not context.get('defer_commit'):
model.Session.commit()
return data
def term_translation_update_many(context, data_dict):
'''Create or update many term translations at once.
:param data: the term translation dictionaries to create or update,
for the format of term translation dictionaries see
:py:func:`~term_translation_update`
:type data: list of dictionaries
:returns: a dictionary with key ``'success'`` whose value is a string
stating how many term translations were updated
:rtype: string
'''
model = context['model']
if not (data_dict.get('data') and isinstance(data_dict.get('data'), list)):
raise ValidationError(
{'error': 'term_translation_update_many needs to have a '
'list of dicts in field data'}
)
context['defer_commit'] = True
action = _get_action('term_translation_update')
for num, row in enumerate(data_dict['data']):
action(context, row)
model.Session.commit()
return {'success': '%s rows updated' % (num + 1)}
## Modifications for rest api
def package_update_rest(context, data_dict):
model = context['model']
id = data_dict.get("id")
request_id = context['id']
pkg = model.Package.get(request_id)
if not pkg:
raise NotFound
if id and id != pkg.id:
pkg_from_data = model.Package.get(id)
if pkg_from_data != pkg:
error_dict = {id:('Cannot change value of key from %s to %s. '
'This key is read-only') % (pkg.id, id)}
raise ValidationError(error_dict)
context["package"] = pkg
context["allow_partial_update"] = False
dictized_package = model_save.package_api_to_dict(data_dict, context)
_check_access('package_update_rest', context, dictized_package)
dictized_after = _get_action('package_update')(context, dictized_package)
pkg = context['package']
package_dict = model_dictize.package_to_api(pkg, context)
return package_dict
def group_update_rest(context, data_dict):
model = context['model']
id = _get_or_bust(data_dict, "id")
group = model.Group.get(id)
context["group"] = group
context["allow_partial_update"] = True
dictized_group = model_save.group_api_to_dict(data_dict, context)
_check_access('group_update_rest', context, dictized_group)
dictized_after = _get_action('group_update')(context, dictized_group)
group = context['group']
group_dict = model_dictize.group_to_api(group, context)
return group_dict
def vocabulary_update(context, data_dict):
'''Update a tag vocabulary.
You must be a sysadmin to update vocabularies.
For further parameters see
:py:func:`~ckan.logic.action.create.vocabulary_create`.
:param id: the id of the vocabulary to update
:type id: string
:returns: the updated vocabulary
:rtype: dictionary
'''
model = context['model']
vocab_id = data_dict.get('id')
if not vocab_id:
raise ValidationError({'id': _('id not in data')})
vocab = model.vocabulary.Vocabulary.get(vocab_id)
if vocab is None:
raise NotFound(_('Could not find vocabulary "%s"') % vocab_id)
data_dict['id'] = vocab.id
if data_dict.has_key('name'):
if data_dict['name'] == vocab.name:
del data_dict['name']
_check_access('vocabulary_update', context, data_dict)
schema = context.get('schema') or schema_.default_update_vocabulary_schema()
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
updated_vocab = model_save.vocabulary_dict_update(data, context)
if not context.get('defer_commit'):
model.repo.commit()
return model_dictize.vocabulary_dictize(updated_vocab, context)
def package_relationship_update_rest(context, data_dict):
# rename keys
key_map = {'id': 'subject',
'id2': 'object',
'rel': 'type'}
# We want 'destructive', so that the value of the subject,
# object and rel in the URI overwrite any values for these
# in params. This is because you are not allowed to change
# these values.
data_dict = logic.action.rename_keys(data_dict, key_map, destructive=True)
relationship_dict = _get_action('package_relationship_update')(context, data_dict)
return relationship_dict
def user_role_update(context, data_dict):
'''Update a user or authorization group's roles for a domain object.
The ``user`` parameter must be given.
You must be authorized to update the domain object.
To delete all of a user or authorization group's roles for domain object,
pass an empty list ``[]`` to the ``roles`` parameter.
:param user: the name or id of the user
:type user: string
:param domain_object: the name or id of the domain object (e.g. a package,
group or authorization group)
:type domain_object: string
:param roles: the new roles, e.g. ``['editor']``
:type roles: list of strings
:returns: the updated roles of all users for the
domain object
:rtype: dictionary
'''
model = context['model']
new_user_ref = data_dict.get('user') # the user who is being given the new role
if not bool(new_user_ref):
raise ValidationError('You must provide the "user" parameter.')
domain_object_ref = _get_or_bust(data_dict, 'domain_object')
if not isinstance(data_dict['roles'], (list, tuple)):
raise ValidationError('Parameter "%s" must be of type: "%s"' % ('role', 'list'))
desired_roles = set(data_dict['roles'])
if new_user_ref:
user_object = model.User.get(new_user_ref)
if not user_object:
raise NotFound('Cannot find user %r' % new_user_ref)
data_dict['user'] = user_object.id
add_user_to_role_func = model.add_user_to_role
remove_user_from_role_func = model.remove_user_from_role
domain_object = logic.action.get_domain_object(model, domain_object_ref)
data_dict['id'] = domain_object.id
# current_uors: in order to avoid either creating a role twice or
# deleting one which is non-existent, we need to get the users\'
# current roles (if any)