-
Notifications
You must be signed in to change notification settings - Fork 2k
/
interfaces.py
1446 lines (1097 loc) · 49 KB
/
interfaces.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
'''A collection of interfaces that CKAN plugins can implement to customize and
extend CKAN.
'''
__all__ = [
'Interface',
'IGenshiStreamFilter', 'IRoutes',
'IMapper', 'ISession',
'IMiddleware',
'IAuthFunctions',
'IDomainObjectModification', 'IGroupController',
'IOrganizationController',
'IPackageController', 'IPluginObserver',
'IConfigurable', 'IConfigurer',
'IActions', 'IResourceUrlChange', 'IDatasetForm',
'IValidators',
'IResourcePreview',
'IResourceView',
'IResourceController',
'IGroupForm',
'ITagController',
'ITemplateHelpers',
'IFacets',
'IAuthenticator',
'ITranslation',
]
from inspect import isclass
from pyutilib.component.core import Interface as _pca_Interface
class Interface(_pca_Interface):
@classmethod
def provided_by(cls, instance):
return cls.implemented_by(instance.__class__)
@classmethod
def implemented_by(cls, other):
if not isclass(other):
raise TypeError("Class expected", other)
try:
return cls in other._implements
except AttributeError:
return False
class IMiddleware(Interface):
'''Hook into Pylons middleware stack
'''
def make_middleware(self, app, config):
'''Return an app configured with this middleware
'''
return app
def make_error_log_middleware(self, app, config):
'''Return an app configured with this error log middleware
'''
return app
class IGenshiStreamFilter(Interface):
'''
Hook into template rendering.
See ckan.lib.base.py:render
'''
def filter(self, stream):
"""
Return a filtered Genshi stream.
Called when any page is rendered.
:param stream: Genshi stream of the current output document
:returns: filtered Genshi stream
"""
return stream
class IRoutes(Interface):
"""
Plugin into the setup of the routes map creation.
"""
def before_map(self, map):
"""
Called before the routes map is generated. ``before_map`` is before any
other mappings are created so can override all other mappings.
:param map: Routes map object
:returns: Modified version of the map object
"""
return map
def after_map(self, map):
"""
Called after routes map is set up. ``after_map`` can be used to
add fall-back handlers.
:param map: Routes map object
:returns: Modified version of the map object
"""
return map
class IMapper(Interface):
"""
A subset of the SQLAlchemy mapper extension hooks.
See http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.MapperExtension
Example::
>>> class MyPlugin(SingletonPlugin):
...
... implements(IMapper)
...
... def after_update(self, mapper, connection, instance):
... log("Updated: %r", instance)
"""
def before_insert(self, mapper, connection, instance):
"""
Receive an object instance before that instance is INSERTed into
its table.
"""
def before_update(self, mapper, connection, instance):
"""
Receive an object instance before that instance is UPDATEed.
"""
def before_delete(self, mapper, connection, instance):
"""
Receive an object instance before that instance is DELETEed.
"""
def after_insert(self, mapper, connection, instance):
"""
Receive an object instance after that instance is INSERTed.
"""
def after_update(self, mapper, connection, instance):
"""
Receive an object instance after that instance is UPDATEed.
"""
def after_delete(self, mapper, connection, instance):
"""
Receive an object instance after that instance is DELETEed.
"""
class ISession(Interface):
"""
A subset of the SQLAlchemy session extension hooks.
"""
def after_begin(self, session, transaction, connection):
"""
Execute after a transaction is begun on a connection
"""
def before_flush(self, session, flush_context, instances):
"""
Execute before flush process has started.
"""
def after_flush(self, session, flush_context):
"""
Execute after flush has completed, but before commit has been called.
"""
def before_commit(self, session):
"""
Execute right before commit is called.
"""
def after_commit(self, session):
"""
Execute after a commit has occured.
"""
def after_rollback(self, session):
"""
Execute after a rollback has occured.
"""
class IDomainObjectModification(Interface):
"""
Receives notification of new, changed and deleted datasets.
"""
def notify(self, entity, operation):
pass
def notify_after_commit(self, entity, operation):
pass
class IResourceUrlChange(Interface):
"""
Receives notification of changed urls.
"""
def notify(self, resource):
pass
class IResourceView(Interface):
'''Add custom view renderings for different resource types.
'''
def info(self):
'''
Returns a dictionary with configuration options for the view.
The available keys are:
:param name: name of the view type. This should match the name of the
actual plugin (eg ``image_view`` or ``recline_view``).
:param title: title of the view type, will be displayed on the
frontend. This should be translatable (ie wrapped on
``toolkit._('Title')``).
:param default_title: default title that will be used if the view is
created automatically (optional, defaults to 'View').
:param default_description: default description that will be used if
the view is created automatically (optional, defaults to '').
:param icon: icon for the view type. Should be one of the
`Font Awesome`_ types without the `icon-` prefix eg. `compass`
(optional, defaults to 'picture').
:param always_available: the view type should be always available when
creating new views regardless of the format of the resource
(optional, defaults to False).
:param iframed: the view template should be iframed before rendering.
You generally want this option to be True unless the view styles
and JavaScript don't clash with the main site theme (optional,
defaults to True).
:param preview_enabled: the preview button should appear on the edit
view form. Some view types have their previews integrated with the
form (optional, defaults to False).
:param full_page_edit: the edit form should take the full page width
of the page (optional, defaults to False).
:param schema: schema to validate extra configuration fields for the
view (optional). Schemas are defined as a dictionary, with the
keys being the field name and the values a list of validator
functions that will get applied to the field. For instance::
{
'offset': [ignore_empty, natural_number_validator],
'limit': [ignore_empty, natural_number_validator],
}
Example configuration object::
{'name': 'image_view',
'title': toolkit._('Image'),
'schema': {
'image_url': [ignore_empty, unicode]
},
'icon': 'picture',
'always_available': True,
'iframed': False,
}
:returns: a dictionary with the view type configuration
:rtype: dict
.. _Font Awesome: http://fortawesome.github.io/Font-Awesome/3.2.1/icons
'''
return {'name': self.__class__.__name__}
def can_view(self, data_dict):
'''
Returns whether the plugin can render a particular resource.
The ``data_dict`` contains the following keys:
:param resource: dict of the resource fields
:param package: dict of the full parent dataset
:returns: True if the plugin can render a particular resource, False
otherwise
:rtype: bool
'''
def setup_template_variables(self, context, data_dict):
'''
Adds variables to be passed to the template being rendered.
This should return a new dict instead of updating the input
``data_dict``.
The ``data_dict`` contains the following keys:
:param resource_view: dict of the resource view being rendered
:param resource: dict of the parent resource fields
:param package: dict of the full parent dataset
:returns: a dictionary with the extra variables to pass
:rtype: dict
'''
def view_template(self, context, data_dict):
'''
Returns a string representing the location of the template to be
rendered when the view is displayed
The path will be relative to the template directory you registered
using the :py:func:`~ckan.plugins.toolkit.add_template_directory`
on the :py:class:`~ckan.plugins.interfaces.IConfigurer.update_config`
method, for instance ``views/my_view.html``.
:param resource_view: dict of the resource view being rendered
:param resource: dict of the parent resource fields
:param package: dict of the full parent dataset
:returns: the location of the view template.
:rtype: string
'''
def form_template(self, context, data_dict):
'''
Returns a string representing the location of the template to be
rendered when the edit view form is displayed
The path will be relative to the template directory you registered
using the :py:func:`~ckan.plugins.toolkit.add_template_directory`
on the :py:class:`~ckan.plugins.interfaces.IConfigurer.update_config`
method, for instance ``views/my_view_form.html``.
:param resource_view: dict of the resource view being rendered
:param resource: dict of the parent resource fields
:param package: dict of the full parent dataset
:returns: the location of the edit view form template.
:rtype: string
'''
class IResourcePreview(Interface):
'''
.. warning:: This interface is deprecated, and is only kept for backwards
compatibility with the old resource preview code. Please
use :py:class:`~ckan.plugins.interfaces.IResourceView` for writing
custom view plugins.
'''
def can_preview(self, data_dict):
'''Return info on whether the plugin can preview the resource.
This can be done in two ways:
1. The old way is to just return ``True`` or ``False``.
2. The new way is to return a dict with three keys:
* ``can_preview`` (``boolean``)
``True`` if the extension can preview the resource.
* ``fixable`` (``string``)
A string explaining how preview for the resource could be enabled,
for example if the ``resource_proxy`` plugin was enabled.
* ``quality`` (``int``)
How good the preview is: ``1`` (poor), ``2`` (average) or
``3`` (good). When multiple preview extensions can preview the
same resource, this is used to determine which extension will
be used.
:param data_dict: the resource to be previewed and the dataset that it
belongs to.
:type data_dict: dictionary
Make sure to check the ``on_same_domain`` value of the resource or the
url if your preview requires the resource to be on the same domain
because of the same-origin policy. To find out how to preview
resources that are on a different domain, read :ref:`resource-proxy`.
'''
def setup_template_variables(self, context, data_dict):
'''
Add variables to c just prior to the template being rendered.
The ``data_dict`` contains the resource and the package.
Change the url to a proxied domain if necessary.
'''
def preview_template(self, context, data_dict):
'''
Returns a string representing the location of the template to be
rendered for the read page.
The ``data_dict`` contains the resource and the package.
'''
class ITagController(Interface):
'''
Hook into the Tag controller. These will usually be called just before
committing or returning the respective object, i.e. all validation,
synchronization and authorization setup are complete.
'''
def before_view(self, tag_dict):
'''
Extensions will recieve this before the tag gets displayed. The
dictionary passed will be the one that gets sent to the template.
'''
return tag_dict
class IGroupController(Interface):
"""
Hook into the Group controller. These will
usually be called just before committing or returning the
respective object, i.e. all validation, synchronization
and authorization setup are complete.
"""
def read(self, entity):
pass
def create(self, entity):
pass
def edit(self, entity):
pass
def authz_add_role(self, object_role):
pass
def authz_remove_role(self, object_role):
pass
def delete(self, entity):
pass
def before_view(self, pkg_dict):
'''
Extensions will recieve this before the group gets
displayed. The dictionary passed will be the one that gets
sent to the template.
'''
return pkg_dict
class IOrganizationController(Interface):
"""
Hook into the Organization controller. These will
usually be called just before committing or returning the
respective object, i.e. all validation, synchronization
and authorization setup are complete.
"""
def read(self, entity):
pass
def create(self, entity):
pass
def edit(self, entity):
pass
def authz_add_role(self, object_role):
pass
def authz_remove_role(self, object_role):
pass
def delete(self, entity):
pass
def before_view(self, pkg_dict):
'''
Extensions will recieve this before the organization gets
displayed. The dictionary passed will be the one that gets
sent to the template.
'''
return pkg_dict
class IPackageController(Interface):
"""
Hook into the package controller.
(see IGroupController)
"""
def read(self, entity):
pass
def create(self, entity):
pass
def edit(self, entity):
pass
def authz_add_role(self, object_role):
pass
def authz_remove_role(self, object_role):
pass
def delete(self, entity):
pass
def after_create(self, context, pkg_dict):
'''
Extensions will receive the validated data dict after the package
has been created (Note that the create method will return a package
domain object, which may not include all fields). Also the newly
created package id will be added to the dict.
'''
pass
def after_update(self, context, pkg_dict):
'''
Extensions will receive the validated data dict after the package
has been updated (Note that the edit method will return a package
domain object, which may not include all fields).
'''
pass
def after_delete(self, context, pkg_dict):
'''
Extensions will receive the data dict (tipically containing
just the package id) after the package has been deleted.
'''
pass
def after_show(self, context, pkg_dict):
'''
Extensions will receive the validated data dict after the package
is ready for display (Note that the read method will return a
package domain object, which may not include all fields).
'''
pass
def before_search(self, search_params):
'''
Extensions will receive a dictionary with the query parameters,
and should return a modified (or not) version of it.
search_params will include an `extras` dictionary with all values
from fields starting with `ext_`, so extensions can receive user
input from specific fields.
'''
return search_params
def after_search(self, search_results, search_params):
'''
Extensions will receive the search results, as well as the search
parameters, and should return a modified (or not) object with the
same structure:
{'count': '', 'results': '', 'facets': ''}
Note that count and facets may need to be adjusted if the extension
changed the results for some reason.
search_params will include an `extras` dictionary with all values
from fields starting with `ext_`, so extensions can receive user
input from specific fields.
'''
return search_results
def before_index(self, pkg_dict):
'''
Extensions will receive what will be given to the solr for
indexing. This is essentially a flattened dict (except for
multli-valued fields such as tags) of all the terms sent to
the indexer. The extension can modify this by returning an
altered version.
'''
return pkg_dict
def before_view(self, pkg_dict):
'''
Extensions will recieve this before the dataset gets
displayed. The dictionary passed will be the one that gets
sent to the template.
'''
return pkg_dict
class IResourceController(Interface):
"""
Hook into the resource controller.
"""
def before_create(self, context, resource):
"""
Extensions will receive this before a resource is created.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param resource: An object representing the resource to be added
to the dataset (the one that is about to be created).
:type resource: dictionary
"""
pass
def after_create(self, context, resource):
"""
Extensions will receive this after a resource is created.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param resource: An object representing the latest resource added
to the dataset (the one that was just created). A key in the
resource dictionary worth mentioning is ``url_type`` which is
set to ``upload`` when the resource file is uploaded instead
of linked.
:type resource: dictionary
"""
pass
def before_update(self, context, current, resource):
"""
Extensions will receive this before a resource is updated.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param current: The current resource which is about to be updated
:type current: dictionary
:param resource: An object representing the updated resource which
will replace the ``current`` one.
:type resource: dictionary
"""
pass
def after_update(self, context, resource):
"""
Extensions will receive this after a resource is updated.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param resource: An object representing the updated resource in
the dataset (the one that was just updated). As with
``after_create``, a noteworthy key in the resource dictionary
``url_type`` which is set to ``upload`` when the resource file
is uploaded instead of linked.
:type resource: dictionary
"""
pass
def before_delete(self, context, resource, resources):
"""
Extensions will receive this before a previously created resource is
deleted.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param resource: An object representing the resource that is about
to be deleted. This is a dictionary with one key: ``id`` which
holds the id ``string`` of the resource that should be deleted.
:type resource: dictionary
:param resources: The list of resources from which the resource will
be deleted (including the resource to be deleted if it existed
in the package).
:type resources: list
"""
pass
def after_delete(self, context, resources):
"""
Extensions will receive this after a previously created resource is
deleted.
:param context: The context object of the current request, this
includes for example access to the ``model`` and the ``user``.
:type context: dictionary
:param resources: A list of objects representing the remaining
resources after a resource has been removed.
:type resource: list
"""
pass
def before_show(self, resource_dict):
'''
Extensions will receive the validated data dict before the resource
is ready for display.
Be aware that this method is not only called for UI display, but also
in other methods like when a resource is deleted because showing a
package is used to get access to the resources in a package.
'''
return resource_dict
class IPluginObserver(Interface):
"""
Plugin to the plugin loading mechanism
"""
def before_load(self, plugin):
"""
Called before a plugin is loaded
This method is passed the plugin class.
"""
def after_load(self, service):
"""
Called after a plugin has been loaded.
This method is passed the instantiated service object.
"""
def before_unload(self, plugin):
"""
Called before a plugin is loaded
This method is passed the plugin class.
"""
def after_unload(self, service):
"""
Called after a plugin has been unloaded.
This method is passed the instantiated service object.
"""
class IConfigurable(Interface):
"""
Pass configuration to plugins and extensions
"""
def configure(self, config):
"""
Called by load_environment
"""
class IConfigurer(Interface):
"""
Configure CKAN (pylons) environment via the ``pylons.config`` object
"""
def update_config(self, config):
"""
Called by load_environment at earliest point when config is
available to plugins. The config should be updated in place.
:param config: ``pylons.config`` object
"""
class IActions(Interface):
"""
Allow adding of actions to the logic layer.
"""
def get_actions(self):
"""
Should return a dict, the keys being the name of the logic
function and the values being the functions themselves.
By decorating a function with the `ckan.logic.side_effect_free`
decorator, the associated action will be made available by a GET
request (as well as the usual POST request) through the action API.
"""
class IValidators(Interface):
"""
Add extra validators to be returned by
:py:func:`ckan.plugins.toolkit.get_validator`.
"""
def get_validators(self):
"""Return the validator functions provided by this plugin.
Return a dictionary mapping validator names (strings) to
validator functions. For example::
{'valid_shoe_size': shoe_size_validator,
'valid_hair_color': hair_color_validator}
These validator functions would then be available when a
plugin calls :py:func:`ckan.plugins.toolkit.get_validator`.
"""
class IAuthFunctions(Interface):
'''Override CKAN's authorization functions, or add new auth functions.'''
def get_auth_functions(self):
'''Return the authorization functions provided by this plugin.
Return a dictionary mapping authorization function names (strings) to
functions. For example::
{'user_create': my_custom_user_create_function,
'group_create': my_custom_group_create}
When a user tries to carry out an action via the CKAN API or web
interface and CKAN or a CKAN plugin calls
``check_access('some_action')`` as a result, an authorization function
named ``'some_action'`` will be searched for in the authorization
functions registered by plugins and in CKAN's core authorization
functions (found in ``ckan/logic/auth/``).
For example when a user tries to create a package, a
``'package_create'`` authorization function is searched for.
If an extension registers an authorization function with the same name
as one of CKAN's default authorization functions (as with
``'user_create'`` and ``'group_create'`` above), the extension's
function will override the default one.
Each authorization function should take two parameters ``context`` and
``data_dict``, and should return a dictionary ``{'success': True}`` to
authorize the action or ``{'success': False}`` to deny it, for
example::
def user_create(context, data_dict=None):
if (some condition):
return {'success': True}
else:
return {'success': False, 'msg': 'Not allowed to register'}
The context object will contain a ``model`` that can be used to query
the database, a ``user`` containing the name of the user doing the
request (or their IP if it is an anonymous web request) and an
``auth_user_obj`` containing the actual model.User object (or None if
it is an anonymous request).
See ``ckan/logic/auth/`` for more examples.
Note that by default, all auth functions provided by extensions are assumed
to require a validated user or API key, otherwise a
:py:class:`ckan.logic.NotAuthorized`: exception will be raised. This check
will be performed *before* calling the actual auth function. If you want
to allow anonymous access to one of your actions, its auth function must
be decorated with the ``auth_allow_anonymous_access`` decorator, available
on the plugins toolkit.
For example::
import ckan.plugins as p
@p.toolkit.auth_allow_anonymous_access
def my_search_action(context, data_dict):
# Note that you can still return {'success': False} if for some
# reason access is denied.
def my_create_action(context, data_dict):
# Unless there is a logged in user or a valid API key provided
# NotAuthorized will be raised before reaching this function.
'''
class ITemplateHelpers(Interface):
'''Add custom template helper functions.
By implementing this plugin interface plugins can provide their own
template helper functions, which custom templates can then access via the
``h`` variable.
See ``ckanext/example_itemplatehelpers`` for an example plugin.
'''
def get_helpers(self):
'''Return a dict mapping names to helper functions.
The keys of the dict should be the names with which the helper
functions will be made available to templates, and the values should be
the functions themselves. For example, a dict like:
``{'example_helper': example_helper}`` allows templates to access the
``example_helper`` function via ``h.example_helper()``.
Function names should start with the name of the extension providing
the function, to prevent name clashes between extensions.
'''
class IDatasetForm(Interface):
'''Customize CKAN's dataset (package) schemas and forms.
By implementing this interface plugins can customise CKAN's dataset schema,
for example to add new custom fields to datasets.
Multiple IDatasetForm plugins can be used at once, each plugin associating
itself with different package types using the ``package_types()`` and
``is_fallback()`` methods below, and then providing different schemas and
templates for different types of dataset. When a package controller action
is invoked, the ``type`` field of the package will determine which
IDatasetForm plugin (if any) gets delegated to.
When implementing IDatasetForm, you can inherit from
``ckan.plugins.toolkit.DefaultDatasetForm``, which provides default
implementations for each of the methods defined in this interface.
See ``ckanext/example_idatasetform`` for an example plugin.
'''
def package_types(self):
'''Return an iterable of package types that this plugin handles.
If a request involving a package of one of the returned types is made,
then this plugin instance will be delegated to.
There cannot be two IDatasetForm plugins that return the same package
type, if this happens then CKAN will raise an exception at startup.
:rtype: iterable of strings
'''
def is_fallback(self):
'''Return ``True`` if this plugin is the fallback plugin.
When no IDatasetForm plugin's ``package_types()`` match the ``type`` of
the package being processed, the fallback plugin is delegated to
instead.
There cannot be more than one IDatasetForm plugin whose
``is_fallback()`` method returns ``True``, if this happens CKAN will
raise an exception at startup.
If no IDatasetForm plugin's ``is_fallback()`` method returns ``True``,
CKAN will use ``DefaultDatasetForm`` as the fallback.
:rtype: boolean
'''
def create_package_schema(self):
'''Return the schema for validating new dataset dicts.
CKAN will use the returned schema to validate and convert data coming
from users (via the dataset form or API) when creating new datasets,
before entering that data into the database.
If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a
plugin can call ``DefaultDatasetForm``'s ``create_package_schema()``
method to get the default schema and then modify and return it.
CKAN's ``convert_to_tags()`` or ``convert_to_extras()`` functions can
be used to convert custom fields into dataset tags or extras for
storing in the database.
See ``ckanext/example_idatasetform`` for examples.
:returns: a dictionary mapping dataset dict keys to lists of validator
and converter functions to be applied to those keys
:rtype: dictionary
'''
def update_package_schema(self):
'''Return the schema for validating updated dataset dicts.
CKAN will use the returned schema to validate and convert data coming
from users (via the dataset form or API) when updating datasets, before
entering that data into the database.
If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a
plugin can call ``DefaultDatasetForm``'s ``update_package_schema()``
method to get the default schema and then modify and return it.
CKAN's ``convert_to_tags()`` or ``convert_to_extras()`` functions can
be used to convert custom fields into dataset tags or extras for
storing in the database.
See ``ckanext/example_idatasetform`` for examples.
:returns: a dictionary mapping dataset dict keys to lists of validator
and converter functions to be applied to those keys
:rtype: dictionary
'''
def show_package_schema(self):
'''
Return a schema to validate datasets before they're shown to the user.
CKAN will use the returned schema to validate and convert data coming
from the database before it is returned to the user via the API or
passed to a template for rendering.
If it inherits from ``ckan.plugins.toolkit.DefaultDatasetForm``, a
plugin can call ``DefaultDatasetForm``'s ``show_package_schema()``
method to get the default schema and then modify and return it.
If you have used ``convert_to_tags()`` or ``convert_to_extras()`` in
your ``create_package_schema()`` and ``update_package_schema()`` then
you should use ``convert_from_tags()`` or ``convert_from_extras()`` in
your ``show_package_schema()`` to convert the tags or extras in the
database back into your custom dataset fields.
See ``ckanext/example_idatasetform`` for examples.