![]()
|
4. Pyro Usage
IntroductionThis chapter will show the Pyro development process: how to build a Pyro application. For starters, let's repeat the scenario from the Introduction chapter here, but with some more detail:
Pyro script toolsBefore using them let us first study the usage of the script tools. Pyro comes with two flavors, Un*x-style shellscripts and Windows/DOS batch files. The Windows-style batch files have the '.bat' extension. When you're using an Amiga, you can use the Un*x-style shellscripts when you've installed the latest 'ExecuteHack'. You might want to make them executable usingprotect +es #? . If it doesn't work, try executing them as regular python scripts, for instance: python nsc list .
All scripts have to be called from a shell command prompt. Most of them accept command line parameters, see below.
Steps 1, 2 and 3: Writing the remote classJust create a Python module containing the classes you want to access remotely. There are some restrictions induced by Pyro:
Static or dynamic proxy?Pyro supports two kinds of client-side proxies: static and dynamic. The most important difference between the two is that dynamic proxies don't require additional code because all logic is embedded in Pyro. Static proxies are defined in a Python module that is generated bypyroc . So you need to distribute these additional source files when you want to use static proxies. So why should you even use a static proxy?
Step 4: Writing the serverInitializationYou should initialize Pyro before using it in your server program. This is done by callingPyro.core.initServer()If you provide the argument '0', no banner is printed, otherwise a short message is printed on the standard output. If the tracelevel is not zero, a startup message is written to the log. This message shows the active configuration options. Create a Pyro DaemonYour server program must create a Pyro Daemon object, which contains all logic necessary for accepting incoming requests and dispatching them to your objects by invoking their methods. You also have to tell the daemon which Name Server to use. When connecting objects to the daemon (see below) it uses this NS to register those objects for you. This is convenient as you don't have to do it yourself.daemon = Pyro.core.Daemon() daemon.useNameServer(ns)You can provide several arguments when creating the Daemon:
The second line tells the daemon to use a certain Name Server ( ns is a proxy for the NS, see the next paragraph how to get this proxy).
It's possible to omit this call but the Daemon will no longer be able to register your objects with the NS. If you didn't register them yourself, it is impossible to find them.
The daemon will log a warning if it doesn't know your NS.
If your daemon is no longer referenced, it might be garbage collected (destroyed) by Python.
Even if you connected Pyro objects to the daemon. So you have to make sure that you keep
a reference to your daemon object at all time. This is recommended anyway because you can then
cleanly terminate your Pyro application by calling Find the Name ServerYou have to get a reference to the Pyro Name Server, which itself is a Pyro object. The easiest way is by using the NS Locator:locator = Pyro.naming.NameServerLocator() ns = locator.getNS() ns now contains a reference. There are more advanced ways to get a
reference to the NS, please read the chapter about the Name Server to
find out about them.
Create object instancesThe objects you create in the server that have to be remotely accessible can't be created bare-bones. They have to be decorated with some logic to fool them into thinking it is a regular python program that invokes their methods. This logic is incorporated in a special generic object base class that is part of the Pyro core:Pyro.core.ObjBase .
There are three ways to achieve this:
Connect object instancesOk, we're going nicely up to this point. We have some objects that even already have gotten a unique ID (that's part of the logicPyro.core.ObjBase gives us). But Pyro still knows nothing about them.
We have to let Pyro know we've created some objects and how they are called. Only then can they be accessed by remote client programs. So let's connect our objects with the Pyro Daemon we've created before (see above):
daemon.connect(obj,'our_object')That done, the daemon has registered our object with the NS too (if you told it where to find the NS, see above). The NS will now have an entry in its table that connects the name "our_object" to our specific object. Note 1: if you don't provide a name, your object is a so-called transient object. The daemon will not register it with the Name Server. This is useful when you create new Pyro objects on the server that are not full-blown objects but rather objects that are only accessible by the code that created them. Have a look at the factory and Bank2 examples if this is not clear. Note 2: the connect method actually returns the URI that will identify this object. You can ignore this if you don't want to use it immediately without having to consult the name service.
Note 3: see the Name Server chapter for more about this and persistent naming. In contrast to the simple (flat) name shown above ("our_object"), Pyro's Name Server supports a hierarchical object naming scheme. For more information about this, see the Name Server chapter. The Daemon handleRequest loopWe're near the end of our server coding effort. The only thing left is the code that sits in a loop and processes incoming requests. Fortunately most of that is handled by a single method in the daemon. For many applications callingdaemon.requestLoop() is enough.
For finer control, you can give a few arguments to the function:
requestLoop(condition, timeout, others, callback)All arguments are optional. The default is that requestLoop enters
an endless loop waiting and handling Pyro requests.
You can specify a condition callable object (for instance, a lambda function)
that is evaluated each cycle of the loop to see if the loop should continue (the condition
must evaluate to 1).
The timeout can be used to adjust the timeout between loop cycles (default=3 seconds). The requestLoop doesn't use the timeout (it only returns
when the optional loop condition is no longer true), the timeout is simply passed
to the underlying handleRequests call. This is required on some
platforms (windows) to cleanly handle break signals like ^C.
The others and callbacks can be used to add your own socket or file
objects to the request handling loop, and act on them if they trigger.
For more details, see the paragraph below.
For those that like to have more control over the request handling loop,
there is also while continueLoop: daemon.handleRequests(3.0) ... do something when a timeout occured ...The timeout value in this example is three seconds. The call to handleRequests returns when the timeout period has passed, or when at least one request was processed.
You could use '0 ' for timeout, but this means the call returns directly if no requests are pending. If you want infinite timeout, use 'None '.
You can also provide additional objects the daemon should wait on (multiplexing), to avoid having to split
your program into multiple threads.
You pass those objects, including a special callback function, as follows:
daemon.handleRequests(timeout, [obj1,obj2,obj3], callback_func)The second argument is a list of objects suitable for passing as ins list to the select system call. The last argument is a callback function.
This function will be called when one of the objects in your list triggers. The function is called with one argument: the list of ready objects.
For more information about this multiplexing issue, see the manual page about the Un*x select system call.
This concludes our server. Full listings can be found in the Example chapter. Step 5: Writing the clientInitializationYou should initialize Pyro before using it in your client program. This is done by callingPyro.core.initClient()If you provide the argument '0', no banner is printed, otherwise a short message is printed on the standard output. If the tracelevel is not zero, a startup message is written to the log. This message shows the active configuration options. Find the Name ServerThis part is identical to the way this is done in the server. See above. Let's assume that the variablens now contains the proxy for the NS.
Find object URIsThere are essentially three ways to find an object URI by name:
Create a proxyYou now have a URI in your posession. But you need an object to call methods on. So you create a proxy object for the URI. You can choose to create a dynamic proxy or a static proxy. In the chapter about Pyro Concepts the difference is explained. For the example below, assume thatpyroc has generated the mymodule_proxy.py proxy module.
obj = Pyro.core.getProxyForURI(uri) # get a dynamic proxy obj = Pyro.core.getAttrProxyForURI(uri) # get a dyn proxy with attribute support obj = mymodule_proxy.myobject(uri) # get a static proxy (also w/ attrib support) # if you're sure that the URI is a real PyroURI object, you can do this: obj = uri.getProxy() # get a dynamic proxy directly from the URI obj = uri.getAttrProxy() # same, but with attribute supportIf you're using attribute proxies, be aware of their limitations (described in the Pyro Concepts chapter, under "Proxy"). Remote method invocationsAnd now what we've all been waiting for: calling remote methods. This is what's Pyro's all about: there is no difference in calling a remote method or calling a method on a regular (local) Python object. Just go on and write:obj.method(arg1, arg2) print obj.getName() a = obj.answerQuestion('What is the meaning of life?') # the following statements only work with a attribute-capable proxy: attrib = obj.attrib obj.sum = obj.sum+1or whatever methods your objects provide. The only thing to keep in mind is that you need a proxy object whose methods you call. This concludes our client. Full listings can be found in the Example chapter. For information on using Pyro's logging/tracing facility, see Runtime control and Logging, below. Steps 6, 7 and 8: Runtime setupThis part is a no-brainer, really. There may be some extra configuration necessary when you're running Pyro behind a firewall, and want to access it from outside the firewall, or have machines with dynamic IP addresses. Please read the chapter "Features and Guidelines" to find out what you have to do. Otherwise it's simple:Starting the Name ServerA Pyro system needs at least one running Name Server. So, if it's not already running, start one using thens utility.
See Pyro script tools. After starting it will print some information and then the Name Server sits in a loop waiting for requests:
irmen@atlantis:~ > projects/Pyro/bin/ns *** Pyro Name Server *** Pyro Server Initialized. Using Pyro V2.4 Will accept shutdown requests. URI written to: /home/irmen/Pyro_NS_URI URI is: PYRO://10.0.0.150:9090/0a000096-08620ada-6697d564-62110a9f Name Server started.The NS writes its URI to a file, as it says. This file can be read by other programs, and this is another -very portable- way to discover the NS. Usually you'll want to use the default mechanism from the NameServerLocator (automatic discovery using broadcasting). This is easier. But if your network doesn't support broadcasting, or the NS can't be reached by a broadcast
(because it sits on another subnet, for instance), you have to use another method to reach the NS.
Running the serverJust start the python module as you do normally. Before starting, you may want to set certain environment variables to change some of Pyro's configuration items. After starting, your server will usually sit in a loop waiting for incoming requests (method calls, actually).Running the clientJust start the python module as you do normally. Before starting, you may want to set certain environment variables to change some of Pyro's configuration items.Runtime control and LoggingControlling the Name ServerYou might want to control the NS while it's running. For instance, to inspect the current registered names or to remove an old name, or to register a new one by hand. You use thensc command-line utility or the xnsc graphical tool for this purpose,
see Pyro script tools.
Controlling PyroPyro has many configuration items that can be changed also during runtime. You might want to set the tracelevel to 3 during a special function, for instance. See the chapter on Installation and Configuration for more information.Tracing (logging)Pyro has two distinct logs: the system log and the user log. The system log is used by Pyro itself. You can use it in your own code too, but generally it's better to use the user log. Also see the chapter on Installation and Configuration for detailed info on how to configure the logging options.
Last NotesPlease be sure to read the chapter on Configuration, the Name Server and the chapter about Pyro's Features and Guidelines.These chapters contain invaluable information about the more detailed aspects and possibilities of Pyro. Also have a look at the extensions package
|