Extending Python and Zope in C
By Michael Roberts2004-12-04
Creating an External Method
The simplest way to call Python from Zope is to make your Python code an External Method. External Methods are Python functions that have been placed into the "Extensions" directory in the Zope installation. Once you have such a Python file there, you can go to any folder, choose "Add External Method", and add a variable that invokes the function in question. Then you can add a DTML field into any page in the folder that displays the result of that invocation. Let's look at a quick example, using our foo.bar Python extension defined above.
First, the extension itself: let's put it into a file named, say, foo.py. Remember, this file goes into the Extensions directory under Zope. For this to work, of course, our foo.pyd created above has to be in the Python library in bin/lib. This is what a simple wrapper for that might look like:
import fooSimple, right? This defines an external method "bar", which can be attached to any folder using the Zope management interface. Then to call our extension from any page in that folder, we simply insert a DTML variable reference like this:
def bar(self,arg):
"""A simple external method."""
return 'Arg length: %d' % foo.bar(arg)
<dtml-var bar('This is a test')>When our page is viewed by the user, the DTML field will be replaced by the text "Arg length: 14". And we've thus extended Zope in C.
Tutorial Pages:
» The Best of Both Worlds
» Extending Python for Fun and Profit
» Writing the Code
» Building the Extension
» Taking it to Zope
» Creating an External Method
» Zope scripts: Cliff Notes version
» Going all out With a Product
» Where to go From Here
» Resources
First published by IBM DeveloperWorks
