The PEAK Developers' Center   TwistedPeak UserPreferences
 
HelpContents Search Diffs Info Edit Subscribe XML Print View

Getting Started

PEAK and Twisted work very well together thanks to the the peak.commands.EventDriven class, a top level container for reactor-based applications. The following shows an XML-RPC server based on Twisted's XML-RPC HOWTO:

from peak.api import binding, commands, running
from twisted.web import xmlrpc, server

class Example(xmlrpc.XMLRPC):
    """An example object to be published."""

    def xmlrpc_echo(self, x):
        """Return all passed args."""
        return x

    def xmlrpc_add(self, a, b):
        """Return sum of arguments."""
        return a + b

class App(commands.EventDriven):
    example = binding.Make(Example)
    server  = binding.Make(lambda self: server.Site(self.example))
    port    = binding.Make(lambda: 7080)
    reactor = binding.Obtain(running.ITwistedReactor)

    __onStart = binding.Make(
        lambda self: self.reactor.listenTCP(self.port, self.server),
        uponAssembly=True
    )

The Example class is lifted verbatim from the HOWTO. Note how the Twisted reactor is obtained in the App class, and how the __onStart method tells the reactor to listen with the given server object and port number.

If saved in a file called twistedpeak.py, this code can be run as follows (on Unix/Linux systems):

PYTHONPATH=. peak import:twistedpeak.App

The example client code from the HOWTO works exactly the same:

>>> import xmlrpclib
>>> s = xmlrpclib.Server('http://localhost:7080/')
>>> s.echo("lala")
'lala'
>>> s.add(1, 2)
3

This code can be used as a starting point for any kind of Twisted application.

Configuration and Binding

The code above is slightly longer than the example shown in the HOWTO, but because of PEAK's component-oriented features, especially its configuration and binding facilities, it is much more flexible. Since commands.EventDriven is a descendent of PEAK's base component class, the App class is also a component class. This primarily means two things:

A component hierarchy always has a "root" object. In our example the root object is created by the peak script, which is installed to an executable directory by PEAK's setup.py installer script. The peak script is a simple launcher which takes a URL-like recipe for finding a "runnable" object to load and run.

...

Notes

This page is a replacement for the one originally created by Joel Boehland in July 2003. Unfortunately his code examples were included in a separate tar archive which has since been lost. Without the code, config files, and shell scripts, the page was no longer usable.

-- John Landahl, March 2005. {{{


PythonPowered
EditText of this page (last modified 2007-03-26 18:24:48)
FindPage by browsing, title search , text search or an index
Or try one of these actions: AttachFile, DeletePage, LikePages, LocalSiteMap, SpellCheck