包以显示基于AT的内容的填充百分比
collective.beancounter的Python项目详细描述
Author: | seletz |
---|---|
Date: | 2007-11-14 |
Revision: | 53844 |
摘要
这个包提供了一个非常简单的viewlet 显示用户填充内容的百分比
设置内容
>>> class Mock(object): ... def __init__(self, **kw): self.__sict__.update(kw)
简介
首先,我们定义一个用于标记be an可计数内容的接口:
>>> from zope import interface >>> class IBeanContable(interface.Interface): ... """ a content which is bean countable """
计数本身非常简单,由适配器完成。我们只是数 default模式中的哪些字段被填充。我们在那里只算 可写字段。从中我们计算出一个百分比。
让我们定义该功能的接口:
>>> class IBeanCounter(interface.Interface): ... percentage = interface.Attribute(u"The percentage filled")
现在让我们创建一些内容类来测试我们的内容:
>>> _ = self.folder.invokeFactory("Document", "doc") >>> doc = self.folder.get(_)
计算default模式中并且被重写/写入的字段数:
>>> 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对象提供adefault适配器:
>>> from collective.beancounter.adapter import ATFieldFilter
- 适配器提供了一个筛选出以下字段的筛选器:
- 不是用户可设置的
- 不在“默认”模式中
- 不在特殊plone字段黑名单中
- 不是布尔字段(它们是真或假,即总是“填充的”)
>>> 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']
好吧,那什么都过滤不了,没关系。现在让我们提供一个适配器 它会过滤掉“title”、“id”和“description”字段:
>>> 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: