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


Python IAnnotations.setdefault方法代码示例

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


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

示例1: storage

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
 def storage(self):
     annotations = IAnnotations(self.context)
     scales = annotations.setdefault(
         'plone.scale',
         ScalesDict()
     )
     if not isinstance(scales, ScalesDict):
         # migrate from PersistentDict to ScalesDict
         new_scales = ScalesDict(scales)
         annotations['plone.scale'] = new_scales
         return new_scales
     return scales
开发者ID:mikejmets,项目名称:plone.scale,代码行数:14,代码来源:storage.py

示例2: EEAReadabilityPlugin

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
class EEAReadabilityPlugin(BrowserView):
    """ EEAReadabilityPlugin
    """

    def __init__(self, context, request):
        """ init """
        self.anno = IAnnotations(context)
        self.context = context
        self.request = request
        self.key = 'readability_scores'

    def __call__(self):
        """ call """
        form_values = json.loads(self.request.form.keys()[0])
        scores = self.anno.setdefault(self.key, {})
        for value in form_values:
            scores[value] = form_values[value]
        return ""

    def get_scores(self):
        """ get_scores """
        scores = self.anno.get(self.key, {})
        key_metrics = {'word_count': 0, 'sentence_count': 0,
                       'readability_value': 0}
        enabled_for = 0
        for value in scores.values():
            if not value.get('readability_value'):
                continue
            enabled_for += 1
            key_metrics['word_count'] += int(value.get('word_count') or 0)
            key_metrics['sentence_count'] += value.get('sentence_count') or 0
            key_metrics['readability_value'] += int(round(float(value.get(
                'readability_value') or 0)))
        # make an average score when we have more than 1 text field for
        # which readability is enabled
        if enabled_for > 1:
            key_metrics['readability_value'] = "{0:.0f}".format(
                            key_metrics['readability_value'] / enabled_for)
        if key_metrics['readability_value'] == 0:
            return {}
        return key_metrics
开发者ID:eea,项目名称:eea.tinymce,代码行数:43,代码来源:readability.py

示例3: get_futures

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
def get_futures(request):
    annotations = IAnnotations(request)
    annotations.setdefault(FUTURES_KEY, {})
    return annotations.get(FUTURES_KEY)
开发者ID:datakurre,项目名称:experimental.promises,代码行数:6,代码来源:adapters.py

示例4: get_promises

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
def get_promises(request):
    alsoProvides(request, IContainsPromises)
    annotations = IAnnotations(request)
    annotations.setdefault(PROMISES_KEY, {})
    return annotations.get(PROMISES_KEY)
开发者ID:datakurre,项目名称:experimental.promises,代码行数:7,代码来源:adapters.py

示例5: VirtualTreeCategoryConfiguration

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
class VirtualTreeCategoryConfiguration(object):
    implements(interfaces.IVirtualTreeCategoryConfiguration)
    adapts(IPloneSiteRoot)

    def __init__(self, context):
        self.context = context
        self.ann = IAnnotations(context)
        # category set here as root is not exposed to the public
        self.storage = self.ann.setdefault(VTC_ANNOTATIONS_KEY, Category("root-node", "Root"))

    def get_enabled(self):
        return self.ann.get(VTC_ENABLED_ANNOTATIONS_KEY, False)

    def set_enabled(self, value):
        self.ann[VTC_ENABLED_ANNOTATIONS_KEY] = value

    enabled = property(get_enabled, set_enabled)

    def _find_node(self, category_path):
        """ Returns node in path or root node """
        if category_path == "/":
            # normalize root category
            category_path = ""
        if not isinstance(category_path, ListTypes):
            path = category_path.split(CATEGORY_SPLITTER)
        else:
            path = category_path
        dpath = self.storage
        if category_path and path:
            # category_path may be empty string (root category)
            for item_id in path:
                if item_id:
                    dpath = dpath.get(item_id, None)
                    if dpath is None:
                        return None
        return dpath

    def list_categories(self, path):
        """ List categories on the specified path only. """
        node = self._find_node(path)
        if node is not None:
            return node.values()
        else:
            return []

    def list_keywords(self, path, recursive=False):
        """ List keywords assigned to specified category """
        result = set()
        node = self._find_node(path)
        if node is not None:
            result.update(node.keywords)
            if recursive:
                for category in node.values():
                    result.update(self.list_keywords(category.path, recursive=True))
        # do not return set, it is not json serializable
        return list(result)

    def add_category(self, category_path, category_name):
        node = self._find_node(category_path)
        norm = getUtility(IIDNormalizer)
        category_id = norm.normalize(safe_unicode(category_name))
        if node.get(category_id, None) is not None:
            Error = interfaces.VirtualTreeCategoriesError
            raise Error("Category already exists")
        else:
            node[category_id] = Category(category_id, category_name)
            logger.info("Category %s (%s) added" % (category_name, category_id))
        return category_id

    def category_tree(self):
        def add_subkeys(node):
            res = []
            for k, category in node.items():
                item = dict(
                    attributes=dict(id=category.id, rel="folder"),
                    state="closed",
                    data=category.title,
                    children=add_subkeys(category),
                )
                res.append(item)
            return res

        return add_subkeys(self.storage)

    def remove_category(self, category_path):
        node = self._find_node(category_path)
        if node is not None:
            parent = node.__parent__
            del parent[node.id]
            logger.info("Category %s (%s) removed" % (node.title, node.id))
            del node
            return True
        else:
            return False

    def rename_category(self, category_path, old_category_id, new_name):
        node = self._find_node(category_path)
        if node is not None:
            parent = node.__parent__
            norm = getUtility(IIDNormalizer)
#.........这里部分代码省略.........
开发者ID:collective,项目名称:collective.virtualtreecategories,代码行数:103,代码来源:storage.py

示例6: handleSaveImport

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]

#.........这里部分代码省略.........
        if not import_file:
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please provide a csv file to import")))
            return


        # File upload is not saved in settings
        file_resource = import_file.data
        file_name = import_file.filename

        if not (import_file.contentType.startswith("text/") or \
            import_file.contentType.startswith("application/csv")):
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please provide a file of type CSV")))
            return
        if import_file.contentType.startswith("application/vnd.ms-excel"):
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please convert your Excel file to CSV first")))
            return



        if data["object_type"] in ['__ignore__', '__stop__']:
            create_new = False
            object_type = None
        else:
            create_new = True
            object_type = data["object_type"]

        # list all the dexterity types
        #dx_types = get_portal_types(self.request)
        #log.debug(dx_types)

        # based from the types, display all the fields
        # fields = get_schema_info(CREATION_TYPE)
        # log.debug(fields)

        # blank header or field means we don't want it
        header_mapping = [d for d in data['header_mapping'] if d['field'] and d['header']]

        matching_headers = dict([(d['field'],d['header']) for d in header_mapping])


        if create_new and not(matching_headers.get('id') or matching_headers.get('title')):
            raise WidgetActionExecutionError('header_mapping',
                Invalid(_(u"If creating new content you need either 'Short Name"
                u" or 'Title' in your data.")))
            return

        if not matching_headers:
            raise WidgetActionExecutionError('header_mapping',
                Invalid(_(u"You must pick which fields should contain your data")))
            return

        primary_key = data["primary_key"]
        if primary_key and not matching_headers.get(primary_key):
            raise WidgetActionExecutionError('primary_key',
                Invalid(_(u"Must be a field selected in Header Mapping")))
            return

        # based from the matching fields, get all the values.
        matching_fields = dict([(d['header'],d['field']) for d in header_mapping])
        import_metadata = dexterity_import(
            self.context,
            file_resource,
            matching_fields,
            object_type,
            create_new,
            primary_key
        )

        existing_count = import_metadata["existing_count"]
        new_count = import_metadata["new_count"]
        ignore_count = import_metadata["ignore_count"]

        api.portal.show_message(
            message=_("import_message_csv_info",  # nopep8
                default=u"""${new_num} items added,
                    ${existing_num} items updated and
                    ${ignore_num} items skipped
                    from ${filename}""",
                mapping={"new_num": new_count,
                    "existing_num": existing_count,
                    "ignore_num": ignore_count,
                    "filename": file_name}),
            request=self.request,
            type="info")

        self.import_metadata = import_metadata

        # Save our sucessful settings to save time next import
        annotations = IAnnotations(self.context)
        settings = annotations.setdefault(KEY, {})
        settings['header_list'] = [d['header'] for d in header_mapping]
        # we will keep making this bigger in case they switch between several CSVs
        settings.setdefault("matching_fields",{}).update(matching_fields)
        settings['primary_key'] = primary_key
        settings['object_type'] = object_type

        return True
开发者ID:collective,项目名称:collective.importexport,代码行数:104,代码来源:import_view.py

示例7: __init__

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     self._md = annotations.setdefault(KEY, PersistentDict())
开发者ID:sarahrichmond,项目名称:org.bccvl.site,代码行数:6,代码来源:metadata.py

示例8: load

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
 def load(self):
     annotations = IAnnotations(self.context)
     return annotations.setdefault(BLOCK_ANNOTATION_KEY,
                                   PersistentMapping())
开发者ID:,项目名称:,代码行数:6,代码来源:

示例9: _storage

# 需要导入模块: from zope.annotation import IAnnotations [as 别名]
# 或者: from zope.annotation.IAnnotations import setdefault [as 别名]
 def _storage(self):
     annotations = IAnnotations(self.context)
     return annotations.setdefault(SYNC_METADATA_KEY, default=OOBTree())
开发者ID:gyst,项目名称:collective.dropboxfolder,代码行数:5,代码来源:adapters.py


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