当前位置: 首页>>代码示例>>Python>>正文


Python interfaces.IContextSourceBinder类代码示例

本文整理汇总了Python中zope.schema.interfaces.IContextSourceBinder的典型用法代码示例。如果您正苦于以下问题:Python IContextSourceBinder类的具体用法?Python IContextSourceBinder怎么用?Python IContextSourceBinder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了IContextSourceBinder类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, values=None, vocabulary=None, source=None, **kw):
        """Initialize object."""
        if vocabulary is not None:
            assert (isinstance(vocabulary, basestring)
                    or IBaseVocabulary.providedBy(vocabulary))
            assert source is None, (
                "You cannot specify both source and vocabulary.")
        elif source is not None:
            vocabulary = source

        assert not (values is None and vocabulary is None), (
               "You must specify either values or vocabulary.")
        assert values is None or vocabulary is None, (
               "You cannot specify both values and vocabulary.")

        self.vocabulary = None
        self.vocabularyName = None
        if values is not None:
            self.vocabulary = SimpleVocabulary.fromValues(values)
        elif isinstance(vocabulary, (unicode, str)):
            self.vocabularyName = vocabulary
        else:
            assert (ISource.providedBy(vocabulary) or
                    IContextSourceBinder.providedBy(vocabulary))
            self.vocabulary = vocabulary
        # Before a default value is checked, it is validated. However, a
        # named vocabulary is usually not complete when these fields are
        # initialized. Therefore signal the validation method to ignore
        # default value checks during initialization of a Choice tied to a
        # registered vocabulary.
        self._init_field = (bool(self.vocabularyName) or
                            IContextSourceBinder.providedBy(self.vocabulary))
        super(Choice, self).__init__(**kw)
        self._init_field = False
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:34,代码来源:_field.py

示例2: choicePersistentFieldAdapter

def choicePersistentFieldAdapter(context):
    """Special handling for Choice fields.
    """
    
    instance = persistentFieldAdapter(context)
    if instance is None:
        return None
    
    if ISource.providedBy(context.vocabulary) or \
            IContextSourceBinder.providedBy(context.vocabulary):
        
        safe = False
        
        # Attempt to reverse engineer a 'values' argument
        if isinstance(context.vocabulary, SimpleVocabulary):
            values = []
            safe = True
            for term in context.vocabulary:
                if term.token == str(term.value) and is_primitive(term.value):
                    values.append(term.value)
                else:
                    safe = False
                    break
            if safe:
                instance._values = values
        
        if not safe:
            __traceback_info__ = "Persistent fields only support named vocabularies " + \
                                    "or vocabularies based on simple value sets."
            return None

    return instance
开发者ID:gforcada,项目名称:plone.registry,代码行数:32,代码来源:fieldfactory.py

示例3: _get_vocabulary

    def _get_vocabulary(self, field):
        """Try to determine the vocabulary for a field, if possible.

        Loosely based on z3c.form.widget.Widget.update().
        """
        # XXX: Refactor this method

        field_vocab = None
        vf = None
        if isinstance(field, Choice):
            # First check whether an override is defined in the configuration
            # for vocabularies we can't (or don't want to) serialize
            override = self._get_vocab_override(field)
            if override is not None:
                return override

            elif field.vocabulary:
                if IVocabularyFactory.providedBy(field.vocabulary):
                    vocabulary = field.vocabulary(None)
                elif IContextSourceBinder.providedBy(field.vocabulary):
                    vocabulary = field.vocabulary(None)
                else:
                    vocabulary = field.vocabulary

            elif field.vocabularyName:
                try:
                    vf = getUtility(
                        IVocabularyFactory, name=field.vocabularyName)
                except ComponentLookupError:
                    pass

                vocabulary = vf(None)

            # Determine whether term order is significant or not
            order_significant = True
            wrapped_vocab = vocabulary
            if IElephantVocabulary.providedBy(vocabulary):
                # VDEX vocaby might be potentially wrapped by Elephant vocabs.
                # In that case, we need to inspect the wrapped vocab to
                # determine whether order is significant or not
                wrapped_vocab = queryUtility(
                    IVocabularyFactory, name=field.vocabulary.vocab)

            if isinstance(wrapped_vocab, VdexVocabulary):
                order_significant = wrapped_vocab.vdex.isOrderSignificant()

            # Build list of terms
            if vocabulary is not None:
                terms = [t.value for t in vocabulary._terms]

                if not order_significant:
                    # For VDEX vocabularies with orderSignificant="false" we
                    # explicitly sort terms to get a stable sort order
                    terms = sorted(terms)

                field_vocab = terms
        return field_vocab
开发者ID:4teamwork,项目名称:opengever.core,代码行数:57,代码来源:field.py

示例4: __init__

    def __init__(self, values=None, vocabulary=None, source=None, **kw):
        """Initialize object."""
        if vocabulary is not None:
            if (not isinstance(vocabulary, string_types)
                    and not IBaseVocabulary.providedBy(vocabulary)):
                raise ValueError('vocabulary must be a string or implement '
                                 'IBaseVocabulary')
            if source is not None:
                raise ValueError(
                    "You cannot specify both source and vocabulary.")
        elif source is not None:
            vocabulary = source

        if (values is None and vocabulary is None):
            raise ValueError(
                "You must specify either values or vocabulary."
            )
        if values is not None and vocabulary is not None:
            raise ValueError(
                "You cannot specify both values and vocabulary."
            )

        self.vocabulary = None
        self.vocabularyName = None
        if values is not None:
            self.vocabulary = SimpleVocabulary.fromValues(values)
        elif isinstance(vocabulary, string_types):
            self.vocabularyName = vocabulary
        else:
            if (not ISource.providedBy(vocabulary)
                    and not IContextSourceBinder.providedBy(vocabulary)):
                raise ValueError('Invalid vocabulary')
            self.vocabulary = vocabulary
        # Before a default value is checked, it is validated. However, a
        # named vocabulary is usually not complete when these fields are
        # initialized. Therefore signal the validation method to ignore
        # default value checks during initialization of a Choice tied to a
        # registered vocabulary.
        self._init_field = (bool(self.vocabularyName) or
                            IContextSourceBinder.providedBy(self.vocabulary))
        super(Choice, self).__init__(**kw)
        self._init_field = False
开发者ID:RadioFreeAsia,项目名称:zope.schema,代码行数:42,代码来源:_field.py

示例5: bind

 def bind(self, object):
     clone = zope.schema.Field.bind(self, object)
     # get registered vocabulary if needed:
     if IContextSourceBinder.providedBy(self.vocabulary):
         clone._vocabulary = self.vocabulary(object)
         assert zope.schema.interfaces.ISource.providedBy(clone.vocabulary)
     elif clone.vocabulary is None and self.vocabularyName is not None:
         vr = zope.schema.vocabulary.getVocabularyRegistry()
         clone._vocabulary = vr.get(object, self.vocabularyName)
         assert zope.schema.interfaces.ISource.providedBy(clone.vocabulary)
     return clone
开发者ID:CGTIC,项目名称:Plone_SP,代码行数:11,代码来源:field.py

示例6: bind

    def bind(self, object):
        """See zope.schema._bootstrapinterfaces.IField."""
        clone = super(Choice, self).bind(object)
        # get registered vocabulary if needed:
        if IContextSourceBinder.providedBy(self.vocabulary):
            clone.vocabulary = self.vocabulary(object)
            assert ISource.providedBy(clone.vocabulary)
        elif clone.vocabulary is None and self.vocabularyName is not None:
            vr = getVocabularyRegistry()
            clone.vocabulary = vr.get(object, self.vocabularyName)
            assert ISource.providedBy(clone.vocabulary)

        return clone
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:13,代码来源:_field.py

示例7: __init__

    def __init__(self, value_type, vocabulary, **kw):
        
        # complain if value_type is not a field
        if value_type is not None and not IField.providedBy(value_type):#IGNORE:E1101
            raise ValueError("'value_type' must be field instance.")
        self.value_type = value_type
        self.vocabulary = None
        self.vocabularyName = None

        if isinstance(vocabulary, (unicode, str)):
            self.vocabularyName = vocabulary
        else: 
            assert (ISource.providedBy(vocabulary) or             #IGNORE:E1101
                    IContextSourceBinder.providedBy(vocabulary))  #IGNORE:E1101
            self.vocabulary = vocabulary
        self._init_field = bool(self.vocabularyName)
        Field.__init__(self, **kw)      # initializing List or Choice would mess up 
                                        # the vocabulary 
        self._init_field = False
开发者ID:tiberiuichim,项目名称:z3ergo,代码行数:19,代码来源:__init__.py

示例8: _resolve_vocabulary

    def _resolve_vocabulary(self, value):
        # Find the vocabulary we should use, raising
        # an exception if this isn't possible, and returning
        # an ISource otherwise.
        vocabulary = self.vocabulary
        if IContextSourceBinder.providedBy(vocabulary) and self.context is not None:
            vocabulary = vocabulary(self.context)
        elif vocabulary is None and self.vocabularyName is not None:
            vr = getVocabularyRegistry()
            try:
                vocabulary = vr.get(self.context, self.vocabularyName)
            except LookupError:
                raise MissingVocabularyError(
                    "Can't validate value without vocabulary named %r" % (self.vocabularyName,)
                ).with_field_and_value(self, value)

        if not ISource.providedBy(vocabulary):
            raise InvalidVocabularyError(vocabulary).with_field_and_value(self, value)

        return vocabulary
开发者ID:marcosptf,项目名称:fedora,代码行数:20,代码来源:_field.py

示例9: __call__

    def __call__(self):
        self.request.response.setHeader(
            'Content-Type', 'application/json; charset=utf-8')

        field = self.request['field']
        slavename = self.request['name']
        slaveid = self.request['slaveID']
        masterid = self.request['masterID']
        value = self.request['value']

        for slave in self.widget.getSlaves():
            # Loop until we find the slave we want
            if slave['name'] != slavename:
                continue

            action = slave.get('action')
            if action not in ['vocabulary', 'value', 'attr']:
                continue

            # --- VALUE --------------------------------------------------------
            if action == 'value':
                value = self.getVocabulary(slave, value, '')
                return json.dumps(translate(value, self.request))

            # --- ATTR- --------------------------------------------------------
            if action == 'attr':
                result = self.getVocabulary(slave, value, None)
                if isinstance(result, dict) and 'attr' in result and 'value' in result:
                    return json.dumps(result)
                else:
                    raise ValueError('Bad attr dictionary for %s.' % slavename)

            # --- VOCABULARY ---------------------------------------------------
            vocabulary = self.getVocabulary(slave, value)

            if isinstance(vocabulary, (tuple, list)):
                vocabulary = self.createVocaabulary(vocabulary)

            widget = self.widget.form.widgets.get(slave['name'])
            if widget is None:
                raise ValueError('Can not find widget: %s' % slave['name'])

            if (IContextSourceBinder.providedBy(vocabulary)
                or IVocabularyTokenized.providedBy(vocabulary)):

                if hasattr(widget.field, 'value_type'):
                    widget.field.value_type.vocabulary = vocabulary
                else:
                    widget.field.vocabulary = vocabulary
                widget.terms = None
                widget.updateTerms()
                widget.update()
                # widget may define items as a property or as a method
                items = widget.items if not callable(widget.items) else widget.items() 
                responseJSON = {'items': items}

                # disable select box if term length = 'disable_length'
                #if len(widget.terms) == slave.get('disable_length', None):
                #    responseJSON['disabled'] = True

                return json.dumps(responseJSON)

        raise ValueError('No such master-slave combo')
开发者ID:damilgra,项目名称:plone.formwidget.masterselect,代码行数:63,代码来源:widget.py


注:本文中的zope.schema.interfaces.IContextSourceBinder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。