如何在 CKAN 2.2 中定义自定义验证器

How can I define custom validator in CKAN 2.2

我需要在我的 CKAN 2.2 扩展中为日期定义一个新的验证器。 IValidators 接口不工作。你能帮帮我吗?

目前有 three different function prototypes 个可用于自定义验证器。下面是一个自定义日期字符串验证器的示例,该验证器使用带有两个参数的原型(文档 link 中的选项 5)。此类型必须 return 字段的最终值(相反,它可以在存储之前更改值):

import ckan.plugins as plugins
import ckan.plugins.toolkit as tk  
from ckan.plugins.toolkit import Invalid

def date_str_validator(value, context):
    valid_date = tk.get_validator('isodate')(value, context)
    if not valid_date or not isinstance(valid_date, datetime.datetime):
        raise Invalid("Invalid date")
    return value

class MyPlugin(plugins.SingletonPlugin, tk.DefaultDatasetForm):

    plugins.implements(plugins.IDatasetForm, inherit=False)

    def _modify_package_schema(self, schema):
        schema.update({
            # Custom extras
            'origination_date':[tk.get_validator('ignore_missing'),
                                date_str_validator,
                                tk.get_converter('convert_to_extras')]
        })
        return schema

    def create_package_schema(self):
        schema = super(MyPlugin, self).create_package_schema()
        schema = self._modify_package_schema(schema)

        return schema

    def update_package_schema(self):
        schema = super(MyPlugin, self).update_package_schema()
        schema = self._modify_package_schema(schema)
        return schema

    def show_package_schema(self):
        schema = super(MyPlugin, self).show_package_schema()

        schema.update({
            # Custom extras
            'origination_date':[tk.get_converter('convert_from_extras'),
                                tk.get_validator('ignore_missing'),
                                date_str_validator]
        })

        return schema

请注意,验证器和转换器是按顺序调用的,因此此处显示的顺序在 _modify_package_schemashow_package_schema 中都很重要。