跳转到主要内容

显示基于AT内容的填充百分比

项目描述

作者:

seletz

日期:
2007-11-14
修订版本:
53844

摘要

此包解决了我的一个需求,提供了一个非常简单的视图小部件,用于显示用户填充内容的百分比。

设置内容

>>> class Mock(object):
...    def __init__(self, **kw): self.__sict__.update(kw)

简介

首先,我们定义一个接口,用于标记可计数的bean内容

>>> from zope import interface
>>> class IBeanContable(interface.Interface):
...     """ a content which is bean countable """

计数本身非常简单,由适配器完成。我们简单地计数默认架构中哪些字段已填充。我们只计算可写字段。从这些字段中,我们计算一个百分比。

让我们为该功能定义一个接口

>>> class IBeanCounter(interface.Interface):
...     percentage = interface.Attribute(u"The percentage filled")

现在让我们创建一些内容类来测试我们的内容

>>> _ = self.folder.invokeFactory("Document", "doc")
>>> doc = self.folder.get(_)

计数在默认架构中且可读/可写的字段

>>> len([f for f in doc.Schema().fields() if f.schemata=="default" and f.mode =="rw"])
4

好的,现在有多少个已填充的?

>>> l = [f for f in doc.Schema().fields() if f.schemata=="default" and f.mode =="rw"]
>>> [f.getName() for f in l if f.get(doc)]
['id']

好的,足够了。现在让我们做相反的操作

>>> [f.getName() for f in l if not f.get(doc)]
['title', 'description', 'text']

好的,足够了。让我们结束这次讨论。

实现

我们有一个适配器

>>> from collective.beancounter.adapter import ATBeanCounter
>>> ct = ATBeanCounter(doc)
>>> print ct.percentage
25.0

完全填写

>>> doc.update( title="muha", text="haha", description="desc")
>>> ct = ATBeanCounter(doc)
>>> print ct.percentage
100.0

太好了。

字段过滤器

您可能需要提供一个适配器来指定一个过滤器,以决定哪些字段被认为是“可计数的”

>>> from collective.beancounter.interfaces import IBeanCounterFieldFilter

我们为AT对象提供了一个默认适配器

>>> from collective.beancounter.adapter import ATFieldFilter
该适配器提供了一个过滤器,可以过滤掉以下字段:
  • 不可由用户设置的字段

  • 不在“默认”架构中的字段

  • 不在特殊的Plone字段黑名单中的字段

  • 不是布尔字段(这些是true或false,即始终“已填充”)

>>> IBeanCounterFieldFilter(doc)
<collective.beancounter.adapter.ATFieldFilter object at ...>

让我们测试一下

>>> from collective.beancounter.adapter import countable_fields
>>> sorted([f.getName() for f in countable_fields(doc)])
['description', 'id', 'text', 'title']

好的,这个过滤器没有过滤任何内容,这是正常的。现在让我们提供一个适配器,它将过滤掉“标题”、“id”和“描述”字段

>>> from zope import component
>>> from Products.Archetypes.interfaces import IBaseObject
>>> class TestFilter(object):
...     component.adapts(IBaseObject)
...     interface.implements(IBeanCounterFieldFilter)
...     def __init__(self,context): self.context = context
...     def __call__(self, field):
...         return field.getName() not in "title id description".split()
>>> component.provideAdapter(TestFilter)

我们现在应该得到我们的适配器

>>> IBeanCounterFieldFilter(doc)
<TestFilter object at ...>

我们现在应该得到除了我们过滤掉的所有字段

>>> set("title id description".split()) & set([f.getName() for f in countable_fields(doc)])
set([])
vim: set ft=rst tw=75 nocin nosi ai sw=4 ts=4 expandtab:

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

collective.beancounter-0.3.1.tar.gz (11.0 kB 查看哈希值)

上传时间 源代码

构建分发

collective.beancounter-0.3.1-py2.4.egg (13.1 kB 查看哈希值)

上传时间 源代码

支持