Python 如何让zope加载我的ZCML?
当我编写一些实用程序时,注册它,然后使用Python 如何让zope加载我的ZCML?,python,zope,zcml,zope.component,Python,Zope,Zcml,Zope.component,当我编写一些实用程序时,注册它,然后使用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 =
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>
但我不知道如何让Global site manager阅读此zcml。您可以将它从其他zcml文件中包含在
<include package="your.package" />
在Python方面,您可以使用模块中的一个API加载ZCML文件:
- zope.configuration.xmlconfig.file
- zope.configuration.xmlconfig.string
- zope.configuration.xmlconfig.xmlconfig
- zope.configuration.xmlconfig.xmlconfig
xmlconfig.string
,它似乎有效,但这是个好主意吗?我不知道
如果你重视自己的理智,就不要使用Zope。实际上,完成这项工作所需的全部工作就是将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))
from zope.configuration import xmlconfig
from calc import eval
xmlconfig.file('configure.zcml')
assert eval('2 + 2') == 4
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>
from zope.configuration import xmlconfig
from calc import eval
xmlconfig.file('configure.zcml')
assert eval('2 + 2') == 4