当我编写一些实用程序时,注册它,然后使用getUtility查询它是可以的:
class IOperation(Interface):
def __call__(a, b):
''' performs operation on two operands '''
class Plus(object):
implements(IOperation)
def __call__(self, a, b):
return a + b
plus = Plus()
class Minus(object):
implements(IOperation)
def __call__(self, a, b):
return a - b
minus = Minus()
gsm = getGlobalSiteManager()
gsm.registerUtility(plus, IOperation, '+')
gsm.registerUtility(minus, IOperation, '-')
def calc(expr):
a, op, b = expr.split()
res = getUtility(IOperation, op)(eval(a), eval(b))
return res
assert calc('2 + 2') == 4现在,据我所知,我可以将实用程序的注册转移到configure.zcml,如下所示:
<configure xmlns="http://namespaces.zope.org/zope">
<utility
component=".calc.plus"
provides=".calc.IOperation"
name="+"
/>
<utility
component=".calc.minus"
provides=".calc.IOperation"
name="-"
/>
</configure>但我不知道如何让globbal网站经理读到这个zcml。
发布于 2014-12-13 17:18:17
实际上,要完成这项工作,所需要的就是将zcml的解析移到另一个文件中。因此,解决方案现在由三个文件组成:
calc.py
from zope.interface import Interface, implements
from zope.component import getUtility
class IOperation(Interface):
def __call__(a, b):
''' performs operation on two operands '''
class Plus(object):
implements(IOperation)
def __call__(self, a, b):
return a + b
class Minus(object):
implements(IOperation)
def __call__(self, a, b):
return a - b
def eval(expr):
a, op, b = expr.split()
return getUtility(IOperation, op)(float(a), float(b))configure.zcml:
<configure xmlns="http://namespaces.zope.org/zope">
<include package="zope.component" file="meta.zcml" />
<utility
factory="calc.Plus"
provides="calc.IOperation"
name="+"
/>
<utility
factory="calc.Minus"
provides="calc.IOperation"
name="-"
/>
</configure>和main.py
from zope.configuration import xmlconfig
from calc import eval
xmlconfig.file('configure.zcml')
assert eval('2 + 2') == 4发布于 2014-11-30 19:31:35
从其他ZCML文件中将其包含在
<include package="your.package" />如果您从头开始编写应用程序,则必须有一个顶级的ZCML文件,该文件首先注册所有ZCML指令(例如<utility>),在您可以在自己包含的ZCML文件中使用它们之前,包括正确的meta.zcml:
<include package="zope.component" file="meta.zcml" />在Python方面,使用zope.configuration.xmlconfig模块中的一个API加载ZCML文件:
哪个?他们有什么不同?我不知道!这一切都被认为是记录在案,但我不能搞清楚它的正面或反面!我在ZODBBrowser中使用了ZODBBrowser,它似乎很有效,但这是个好主意吗?我不知道!
如果你重视你的理智,就不要用佐普。
https://stackoverflow.com/questions/27174914
复制相似问题