import a class and use the method python
-
25-06-2021 - |
Question
I have a file structure like this: products
-product
- content
- MyContent.py
- Tool.py
In Tool.py, I have
from AccessControl import ClassSecurityInfo
from OFS.SimpleItem import SimpleItem
from Products.CMFCore.utils import UniqueObject
class Tool(PropertyManager, UniqueObject, SimpleItem):
@staticmethod
security.declarePublic('convert_to_lower')
def convert_to_lower(data):
return data.lower()
In MyContent.py, I Tool access this class method, so I did:
from Product.Tool import Tool
from Product.Content.ATContentTypes.content.base import ATCTContent
class MyContent(BaseContent):
def new_definition(self):
print Tool.convert_to_lower("ABCD")
I can't seem to find what I am doing wrong here. I instantiate the object of MyContent with:
mycontent = MyContent()
mycontent.new_definition()
But, when I run it, it gives me error saying that the method convert_to_lower is not defined. Note: the convert_to_lower() is just a simple example of what I am trying to do.
La solution
You probably made a typo in your example; the correct spelling would be
@staticmethod
, not@staticclass
. Since the latter would produce a name error I'm sure you knew that already. :-)There is no point in putting a security declaration on a static method, that's only applicable to class methods (the declaration is stored on the class, not the method).
The decorator is being applied to the result of the security declaration line, not the function definition below it. In other words, you now have a
None
static method on your class.
The usual way to provide such utility methods in Plone is to use a ZCA utility registration though, not a static method.
Autres conseils
The approach above appears weird. Your tool uses PropertyManager, UniqueObject, SimpleItem as base classes - this implies that your tool is a persistent object. So you want to get hold of the tool by using
my_tool = getToolByName(self, tool_name)
result = my_tool.my_method()
Or you implement your functionality as a Zope utility and look it up using getUtility().
However writing a persistent tool and then trying to just important the tool does not make much sense. If your code does not deal with persistent object or is just a utility method having nothing in mind with core Zope or Plone functionality: make it a "normal" class without the base classes above and import it they you are trying to do.