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


Python OrderedDict.iteritems方法代码示例

本文整理汇总了Python中sqlalchemy.util.OrderedDict.iteritems方法的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict.iteritems方法的具体用法?Python OrderedDict.iteritems怎么用?Python OrderedDict.iteritems使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy.util.OrderedDict的用法示例。


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

示例1: FieldSet

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]
class FieldSet(BaseFieldSet):
    def __init__(self, model, session=None, data=None, prefix=None):
        self._fields = OrderedDict()
        self._render_fields = OrderedDict()
        self.model = self.session = None
        BaseFieldSet.rebind(self, model, data=data)
        self.prefix = prefix
        self.model = model
        self.readonly = False
        self.focus = True
        self._errors = []
        focus = True
        for k, v in model().iteritems():
            if not k.startswith('_'):
                try:
                    t = getattr(fatypes, v.__class__.__name__.replace('Property',''))
                except AttributeError:
                    raise NotImplementedError('%s is not mapped to a type' % v.__class__)
                else:
                    self.add(Field(name=k, type=t))
                    if v.required:
                        self._fields[k].validators.append(validators.required)

    def bind(self, model, session=None, data=None):
        """Bind to an instance"""
        if not (model or session or data):
            raise Exception('must specify at least one of {model, session, data}')
        if not model:
            if not self.model:
                raise Exception('model must be specified when none is already set')
            model = fields._pk(self.model) is None and type(self.model) or self.model
        # copy.copy causes a stacktrace on python 2.5.2/OSX + pylons.  unable to reproduce w/ simpler sample.
        mr = object.__new__(self.__class__)
        mr.__dict__ = dict(self.__dict__)
        # two steps so bind's error checking can work
        mr.rebind(model, session, data)
        mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
        if self._render_fields:
            mr._render_fields = OrderedDict([(field.key, field) for field in
                                             [field.bind(mr) for field in self._render_fields.itervalues()]])
        return mr

    def rebind(self, model, session=None, data=None):
        if model:
            if isinstance(model, type):
                try:
                    model = model()
                except:
                    raise Exception('%s appears to be a class, not an instance, but FormAlchemy cannot instantiate it.  (Make sure all constructor parameters are optional!)' % model)
            self.model = model
            self._bound_pk = model._doc.get('_id', None)
        if data is None:
            self.data = None
        elif hasattr(data, 'getall') and hasattr(data, 'getone'):
            self.data = data
        else:
            try:
                self.data = SimpleMultiDict(data)
            except:
                raise Exception('unsupported data object %s.  currently only dicts and Paste multidicts are supported' % self.data)
开发者ID:abourget,项目名称:formalchemy-abourget,代码行数:62,代码来源:couchdb.py

示例2: FieldSet

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]
class FieldSet(BaseFieldSet):
    def __init__(self, model, session=None, data=None, prefix=None):
        self._fields = OrderedDict()
        self._render_fields = OrderedDict()
        self.model = self.session = None
        self.prefix = prefix
        self.model = model
        self.readonly = False
        self.focus = True
        self._errors = []
        self.iface = model
        focus = True
        for name, field in schema.getFieldsInOrder(model):
            try:
                t = FIELDS_MAPPING[field.__class__]
            except KeyError:
                raise NotImplementedError('%s is not mapped to a type' % field.__class__)
            else:
                self.add(Field(name=name, type=t))
                if field.title:
                    self._fields[name].label_text = field.title
                if field.required:
                    self._fields[name].validators.append(validators.required)

    def bind(self, model, session=None, data=None):
        """Bind to an instance"""
        if not (model or session or data):
            raise Exception('must specify at least one of {model, session, data}')
        if not model:
            if not self.model:
                raise Exception('model must be specified when none is already set')
            model = fields._pk(self.model) is None and type(self.model) or self.model
        # copy.copy causes a stacktrace on python 2.5.2/OSX + pylons.  unable to reproduce w/ simpler sample.
        mr = object.__new__(self.__class__)
        mr.__dict__ = dict(self.__dict__)
        # two steps so bind's error checking can work
        mr.rebind(model, session, data)
        mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
        if self._render_fields:
            mr._render_fields = OrderedDict([(field.key, field) for field in
                                             [field.bind(mr) for field in self._render_fields.itervalues()]])
        return mr

    def rebind(self, model, session=None, data=None):
        if model:
            if not self.iface.providedBy(model):
                raise Exception('%r is not provided by %r' % (self.iface, model))
            self.model = model
            self._bound_pk = None
        if data is None:
            self.data = None
        elif hasattr(data, 'getall') and hasattr(data, 'getone'):
            self.data = data
        else:
            try:
                self.data = SimpleMultiDict(data)
            except:
                raise Exception('unsupported data object %s.  currently only dicts and Paste multidicts are supported' % self.data)
开发者ID:abourget,项目名称:formalchemy-abourget,代码行数:60,代码来源:__init__.py

示例3: FieldSet

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]
class FieldSet(BaseFieldSet):
    """FieldSet aware of zope schema. See :class:`formalchemy.forms.FieldSet` for full api."""

    _fields_mapping = {
        schema.TextLine: fatypes.Unicode,
        schema.Text: fatypes.Unicode,
        schema.Int: fatypes.Integer,
        schema.Bool: fatypes.Boolean,
        schema.Float: fatypes.Float,
        schema.Date: fatypes.Date,
        schema.Datetime: fatypes.DateTime,
        schema.Time: fatypes.Time,
        schema.Choice: fatypes.Unicode,
        schema.List: fatypes.List,
    }

    def __init__(self, model, session=None, data=None, prefix=None):
        self._fields = OrderedDict()
        self._render_fields = OrderedDict()
        self.model = self.session = None
        self.prefix = prefix
        self.model = model
        self.readonly = False
        self.focus = True
        self._errors = []
        self._bound_pk = None
        self.data = None
        self.validator = None
        self.iface = model
        focus = True
        for name, field in schema.getFieldsInOrder(model):
            klass = field.__class__
            try:
                t = self._fields_mapping[klass]
            except KeyError:
                raise NotImplementedError('%s is not mapped to a type' % klass)
            else:
                self.append(Field(name=name, type=t))
                self._fields[name].label_text = field.title or name
                if field.description:
                    self._fields[name].set(instructions=field.description)
                if field.required:
                    self._fields[name].validators.append(validators.required)
                if klass is schema.Text:
                    self._fields[name].set(renderer=fields.TextAreaFieldRenderer)
                if klass is schema.List:
                    value_type = self.model[name].value_type
                    if isinstance(value_type, schema.Choice):
                        self._fields[name].set(options=value_type, multiple=True)
                    else:
                        self._fields[name].set(multiple=True)
                elif klass is schema.Choice:
                    self._fields[name].set(renderer=fields.SelectFieldRenderer,
                                           options=self.model[name])

    def bind(self, model, session=None, data=None):
        if not (model is not None or session or data):
            raise Exception('must specify at least one of {model, session, data}')
        # copy.copy causes a stacktrace on python 2.5.2/OSX + pylons.  unable to reproduce w/ simpler sample.
        mr = object.__new__(self.__class__)
        mr.__dict__ = dict(self.__dict__)
        # two steps so bind's error checking can work
        mr.rebind(model, session, data)
        mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
        if self._render_fields:
            mr._render_fields = OrderedDict([(field.key, field) for field in
                                             [field.bind(mr) for field in self._render_fields.itervalues()]])
        return mr

    def gen_model(self, model=None, dict_like=False, **kwargs):
        if model and self.iface.providedBy(model):
            return model
        factory = gen_model(self.iface, model, dict_like=dict_like)
        model = factory(context=model, **kwargs)
        return model

    def rebind(self, model, session=None, data=None):
        if model is not self.iface:
            if model and not self.iface.providedBy(model):
                if getattr(model, '__implemented__', None) is not None:
                    raise ValueError('%r does not provide %r' % (model, self.iface))
                model = self.gen_model(model)
        self.model = model
        self._bound_pk = fields._pk(model)
        if data is None:
            self.data = None
        elif hasattr(data, 'getall') and hasattr(data, 'getone'):
            self.data = data
        else:
            try:
                self.data = SimpleMultiDict(data)
            except:
                raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
开发者ID:Alwnikrotikz,项目名称:formalchemy,代码行数:95,代码来源:__init__.py

示例4: ModelRenderer

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]

#.........这里部分代码省略.........
        if not isinstance(field, fields.Field):
            raise ValueError('Can only add Field objects; got %s instead' % field)
        field.parent = self
        _fields = self._render_fields or self._fields
        _fields[field.name] = field

    def add(self, field):
        warnings.warn(DeprecationWarning('FieldSet.add is deprecated. Use FieldSet.append instead. Your validator will break in FA 1.5'))
        self.append(field)

    def extend(self, fields):
        """Add a list of fields. By default, each Field will be included in the
        rendered form or table."""
        for field in fields:
            self.append(field)

    def insert(self, field, new_field):
        """Insert a new field *before* an existing field.

        This is like the normal ``insert()`` function of ``list`` objects. It
        takes the place of the previous element, and pushes the rest forward.
        """
        fields_ = self._render_fields or self._fields
        if not isinstance(new_field, fields.Field):
            raise ValueError('Can only add Field objects; got %s instead' % field)
        if isinstance(field, fields.AbstractField):
            try:
                index = fields_.keys().index(field.name)
            except ValueError:
                raise ValueError('%s not in fields' % field.name)
        else:
            raise TypeError('field must be a Field. Got %r' % field)
        new_field.parent = self
        items = list(fields_.iteritems()) # prepare for Python 3
        items.insert(index, (new_field.name, new_field))
        if self._render_fields:
            self._render_fields = OrderedDict(items)
        else:
            self._fields = OrderedDict(items)

    def insert_after(self, field, new_field):
        """Insert a new field *after* an existing field.

        Use this if your business logic requires to add after a certain field,
        and not before.
        """
        fields_ = self._render_fields or self._fields
        if not isinstance(new_field, fields.Field):
            raise ValueError('Can only add Field objects; got %s instead' % field)
        if isinstance(field, fields.AbstractField):
            try:
                index = fields_.keys().index(field.name)
            except ValueError:
                raise ValueError('%s not in fields' % field.name)
        else:
            raise TypeError('field must be a Field. Got %r' % field)
        new_field.parent = self
        items = list(fields_.iteritems())
        new_item = (new_field.name, new_field)
        if index + 1 == len(items): # after the last element ?
            items.append(new_item)
        else:
            items.insert(index + 1, new_item)
        if self._render_fields:
            self._render_fields = OrderedDict(items)
        else:
开发者ID:svarks,项目名称:bind_config_manager,代码行数:70,代码来源:base.py

示例5: FieldSet

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]
class FieldSet(BaseFieldSet):
    _mapping = {
        descriptors.rdfSingle: fatypes.String,
        descriptors.rdfMultiple: fatypes.List,
        descriptors.rdfList: fatypes.List,
    }

    def __init__(self, model, session=None, data=None, prefix=None):
        self._fields = OrderedDict()
        self._render_fields = OrderedDict()
        self.model = self.session = None
        BaseFieldSet.rebind(self, model, data=data)
        self.prefix = prefix
        self.model = model
        self.readonly = False
        self.focus = True
        self._errors = []
        focus = True
        for k, v in model.__dict__.iteritems():
            if not k.startswith("_"):
                descriptor = type(v)
                t = self._mapping.get(descriptor)
                if t:
                    self.append(Field(name=k, type=t))

    def bind(self, model=None, session=None, data=None):
        """Bind to an instance"""
        if not (model or session or data):
            raise Exception("must specify at least one of {model, session, data}")
        if not model:
            if not self.model:
                raise Exception("model must be specified when none is already set")
            else:
                model = self.model()
        # copy.copy causes a stacktrace on python 2.5.2/OSX + pylons.  unable to reproduce w/ simpler sample.
        mr = object.__new__(self.__class__)
        mr.__dict__ = dict(self.__dict__)
        # two steps so bind's error checking can work
        mr.rebind(model, session, data)
        mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
        if self._render_fields:
            mr._render_fields = OrderedDict(
                [(field.key, field) for field in [field.bind(mr) for field in self._render_fields.itervalues()]]
            )
        return mr

    def rebind(self, model, session=None, data=None):
        if model:
            if isinstance(model, type):
                try:
                    model = model()
                except:
                    raise Exception(
                        "%s appears to be a class, not an instance, but FormAlchemy cannot instantiate it.  (Make sure all constructor parameters are optional!)"
                        % model
                    )
            self.model = model
            self._bound_pk = None
        if data is None:
            self.data = None
        elif hasattr(data, "getall") and hasattr(data, "getone"):
            self.data = data
        else:
            try:
                self.data = SimpleMultiDict(data)
            except:
                raise Exception(
                    "unsupported data object %s.  currently only dicts and Paste multidicts are supported" % self.data
                )
开发者ID:Alwnikrotikz,项目名称:formalchemy,代码行数:71,代码来源:rdf.py

示例6: ModelRenderer

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]

#.........这里部分代码省略.........
        >>> fs.configure(include=[fs.name, fs.email])
        
        or

        >>> fs.configure(exclude=[fs.orders])

        Of course, you can include modifications to a field in the `include`
        parameter, such as here, to render name and options-as-checkboxes:

        >>> fs.configure(include=[fs.name, fs.orders.checkbox()])
        """
        self._render_fields = OrderedDict([(field.key, field) for field in self._get_fields(pk, exclude, include, options)])

    def bind(self, model=None, session=None, data=None):
        """
        Return a copy of this FieldSet or Grid, bound to the given
        `model`, `session`, and `data`. The parameters to this method are the
        same as in the constructor.

        Often you will create and `configure` a FieldSet or Grid at application
        startup, then `bind` specific instances to it for actual editing or display.
        """
        if not (model or session or data):
            raise Exception('must specify at least one of {model, session, data}')
        if not model:
            if not self.model:
                raise Exception('model must be specified when none is already set')
            model = fields._pk(self.model) is None and type(self.model) or self.model
        # copy.copy causes a stacktrace on python 2.5.2/OSX + pylons.  unable to reproduce w/ simpler sample.
        mr = object.__new__(self.__class__)
        mr.__dict__ = dict(self.__dict__)
        # two steps so bind's error checking can work
        ModelRenderer.rebind(mr, model, session, data)
        mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
        if self._render_fields:
            mr._render_fields = OrderedDict([(field.key, field) for field in
                                             [field.bind(mr) for field in self._render_fields.itervalues()]])
        return mr

    def rebind(self, model=None, session=None, data=None):
        """
        Like `bind`, but acts on this instance.  No return value.
        Not all parameters are treated the same; specifically, what happens if they are NOT specified is different:
           * if `model` is not specified, the old model is used
           * if `session` is not specified, FA tries to re-guess session from the model
           * if data is not specified, it is rebound to None.
        """
        original_model = model
        if model:
            if isinstance(model, type):
                try:
                    model = model()
                except:
                    raise Exception('%s appears to be a class, not an instance, but FormAlchemy cannot instantiate it.  (Make sure all constructor parameters are optional!)' % model)
                # take object out of session, if present
                try:
                    _obj_session = object_session(model)
                except AttributeError:
                    pass # non-SA object; doesn't need session
                else:
                    if _obj_session:
                        _obj_session.expunge(model)
            elif object_session(model):
                # for instances of mapped classes, require that the instance have a PK already
                try:
                    class_mapper(type(model))
开发者ID:abourget,项目名称:formalchemy-abourget,代码行数:70,代码来源:base.py

示例7: CospreadDataRecords

# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import iteritems [as 别名]

#.........这里部分代码省略.........
            if essential_title_set & set(row):
                next_row = self._data.get_row(row_index + 1)
                last_title = None
                for col_index, row_val in enumerate(row):
                    if not row_val:
                        title = None
                        if last_title in self.column_spreading_titles:
                            title = "%s - %s" % (last_title, next_row[col_index])
                    else:
                        title = row_val.strip().replace("  ", " ")
                        last_title = title
                    if title in self.column_spreading_titles:
                        title = "%s - %s" % (title, next_row[col_index])
                    titles.append(title)
                return (titles, row_index + 1)
            row_index += 1

    def create_title_mapping(self):
        """Creates a mapping between the spreadsheet\'s actual column
        titles and the normalised versions.

        Results in self.title_map and self.title_reverse_map which are
        comprehensive for this spreadsheet.

        """
        self.title_map = OrderedDict()
        for title in self.titles:
            for norm_title, regex in self.title_normaliser:
                if regex.match(title):
                    self.title_map[title] = norm_title
                    break
            else:
                raise AssertionError("Did not recognise title: %r" % title)
        self.title_reverse_map = dict((v, k) for k, v in self.title_map.iteritems())
        # check all keys map both ways
        unmatched_keys = set(self.title_map.keys()) - set(self.title_reverse_map.values())
        if unmatched_keys:
            msg = "Columns not identified by REs: %r" % (
                set(self.title_map.keys()) - set(self.title_reverse_map.values())
            )
            msg += "\nColumns over identified by REs: %r" % (
                set(self.title_reverse_map.keys()) - set(self.title_map.values())
            )
            raise AssertionError(msg)

    @property
    def records(self):
        """Returns package records.
        * Collates packages with download_url in multiple rows in resources.
        * Collapses 'Standard' / 'Other' column pairs into single value.
        * Renames columns to standard names.
        """
        current_record = None
        package_identity_column = "Package name" if not self.generate_names else "Title"
        self.create_title_mapping()
        try:

            def get_record_key(record_, standard_key):
                alt_key = self.title_reverse_map.get(standard_key)
                if alt_key and alt_key in record_:
                    return alt_key
                else:
                    return standard_key
                return record_[self.title_reverse_map[property]]

            for record in super(CospreadDataRecords, self).records:
开发者ID:okfn,项目名称:ckanext-dgu,代码行数:70,代码来源:cospread.py


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