Sophie

Sophie

distrib > Mageia > 4 > x86_64 > by-pkgid > c3732731228538f6126cae930c10ad71 > files > 184

python-pyro4-4.21-3.mga4.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Clients: Calling remote objects &mdash; Pyro 4.21 documentation</title>
    
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '4.21',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Pyro 4.21 documentation" href="index.html" />
    <link rel="next" title="Servers: publishing objects" href="servercode.html" />
    <link rel="prev" title="Command line tools" href="commandline.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="servercode.html" title="Servers: publishing objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="commandline.html" title="Command line tools"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Pyro 4.21 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="clients-calling-remote-objects">
<h1>Clients: Calling remote objects<a class="headerlink" href="#clients-calling-remote-objects" title="Permalink to this headline">¶</a></h1>
<p>This chapter explains how you write code that calls remote objects.
Often, a program that calls methods on a Pyro object is called a <em>client</em> program.
(The program that provides the object and actually runs the methods, is the <em>server</em>.
Both roles can be mixed in a single program.)</p>
<p>Make sure you are familiar with Pyro&#8217;s <a class="reference internal" href="tutorials.html#keyconcepts"><em>Key concepts</em></a> before reading on.</p>
<div class="section" id="object-discovery">
<span id="id1"></span><h2>Object discovery<a class="headerlink" href="#object-discovery" title="Permalink to this headline">¶</a></h2>
<p>To be able to call methods on a Pyro object, you have to tell Pyro where it can find
the actual object. This is done by creating an appropriate URI, which contains amongst
others the object name and the location where it can be found.
You can create it in a number of ways.</p>
<ul>
<li><dl class="first docutils">
<dt>directly use the object name and location.</dt>
<dd><p class="first">This is the easiest way and you write an URI directly like this: <tt class="docutils literal"><span class="pre">PYRO:someobjectid&#64;servername:9999</span></tt>
It requires that you already know the object id, servername, and port number.
You could choose to use fixed object names and fixed port numbers to connect Pyro daemons on.
For instance, you could decide that your music server object is always called &#8220;musicserver&#8221;,
and is accessible on port 9999 on your server musicbox.my.lan. You could then simply use:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">uri_string</span> <span class="o">=</span> <span class="s">&quot;PYRO:musicserver@musicbox.my.lan:9999&quot;</span>
<span class="c"># or use Pyro4.URI(&quot;...&quot;) for an URI object instead of a string</span>
</pre></div>
</div>
<p class="last">Most examples that come with Pyro simply ask the user to type this in on the command line,
based on what the server printed. This is not very useful for real programs,
but it is a simple way to make it work. You could write the information to a file
and read that from a file share (only slightly more useful, but it&#8217;s just an idea).</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>use a logical name and look it up in the name server.</dt>
<dd><p class="first">A more flexible way of locating your objects is using logical names for them and storing
those in the Pyro name server. Remember that the name server is like a phone book, you look
up a name and it gives you the exact location.
To continue on the previous bullet, this means your clients would only have to know the
logical name &#8220;musicserver&#8221;. They can then use the name server to obtain the proper URI:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Pyro4</span>
<span class="n">nameserver</span> <span class="o">=</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">locateNS</span><span class="p">()</span>
<span class="n">uri</span> <span class="o">=</span> <span class="n">nameserver</span><span class="o">.</span><span class="n">lookup</span><span class="p">(</span><span class="s">&quot;musicserver&quot;</span><span class="p">)</span>
<span class="c"># ... uri now contains the URI with actual location of the musicserver object</span>
</pre></div>
</div>
<p class="last">You might wonder how Pyro finds the Name server. This is explained in the separate chapter <a class="reference internal" href="nameserver.html"><em>Name Server</em></a>.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>use a logical name and let Pyro look it up in the name server for you.</dt>
<dd><p class="first">Very similar to the option above, but even more convenient, is using the <em>meta</em>-protocol
identifier <tt class="docutils literal"><span class="pre">PYRONAME</span></tt> in your URI string. It lets Pyro know that it should lookup
the name following it, in the name server. Pyro should then
use the resulting URI from the name server to contact the actual object.
So this means you can write:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">uri_string</span> <span class="o">=</span> <span class="s">&quot;PYRONAME:musicserver&quot;</span>
<span class="c"># or Pyro4.URI(&quot;PYRONAME:musicserver&quot;) for an URI object</span>
</pre></div>
</div>
<p class="last">You can use this URI everywhere you would normally use a normal uri (using <tt class="docutils literal"><span class="pre">PYRO</span></tt>).
Everytime Pyro encounters the <tt class="docutils literal"><span class="pre">PYRONAME</span></tt> uri it will use the name server automatically
to look up the object for you. <a class="footnote-reference" href="#pyroname" id="id2">[1]</a></p>
</dd>
</dl>
</li>
</ul>
<table class="docutils footnote" frame="void" id="pyroname" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[1]</a></td><td>this is not very efficient if it occurs often. Have a look at the <a class="reference internal" href="tipstricks.html"><em>Tips &amp; Tricks</em></a>
chapter for some hints about this.</td></tr>
</tbody>
</table>
</div>
<div class="section" id="calling-methods">
<h2>Calling methods<a class="headerlink" href="#calling-methods" title="Permalink to this headline">¶</a></h2>
<p>Once you have the location of the Pyro object you want to talk to, you create a Proxy for it.
Normally you would perhaps create an instance of a class, and invoke methods on that object.
But with Pyro, your remote method calls on Pyro objects go trough a proxy.
The proxy can be treated as if it was the actual object, so you write normal python code
to call the remote methods and deal with the return values, or even exceptions:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Continuing our imaginary music server example.</span>
<span class="c"># Assume that uri contains the uri for the music server object.</span>

<span class="n">musicserver</span> <span class="o">=</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">Proxy</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">musicserver</span><span class="o">.</span><span class="n">load_playlist</span><span class="p">(</span><span class="s">&quot;90s rock&quot;</span><span class="p">)</span>
    <span class="n">musicserver</span><span class="o">.</span><span class="n">play</span><span class="p">()</span>
    <span class="k">print</span> <span class="s">&quot;Currently playing:&quot;</span><span class="p">,</span> <span class="n">musicserver</span><span class="o">.</span><span class="n">current_song</span><span class="p">()</span>
<span class="k">except</span> <span class="n">MediaServerException</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&quot;Couldn&#39;t select playlist or start playing&quot;</span>
</pre></div>
</div>
<p>For normal usage, there&#8217;s not a single line of Pyro specific code once you have a proxy!</p>
</div>
<div class="section" id="serialization">
<span id="object-serialization"></span><h2>Serialization<a class="headerlink" href="#serialization" title="Permalink to this headline">¶</a></h2>
<p>Pyro will serialize the objects that you pass to the remote methods, so they can be sent across
a network connection. Depending on the serializer that is being used, there will be some limitations
on what objects you can use.</p>
<ul class="simple">
<li>serpent: serializes into Python literal expressions. Accepts quite a lot of different types.
Many will be serialized as dicts. You might need to explicitly translate literals back to specific types
on the receiving end if so desired, because most custom classes aren&#8217;t dealt with automatically.
Requires third party library module.</li>
<li>json: more restricted as serpent, less types supported. Part of Python&#8217;s standard library.</li>
<li>marshal: a very limited but fast serializer. Can deal with a small range of builtin types only, no custom classes can be serialized. Part of the standard library.</li>
<li>pickle: the legacy serializer. Fast and supports almost all types. Has security problems though.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Since Pyro 4.20 the default serializer is &#8220;<tt class="docutils literal"><span class="pre">serpent</span></tt>&#8221;.
Before that, it used to be &#8220;<tt class="docutils literal"><span class="pre">pickle</span></tt>&#8221;.
Serpent is less expressive (not all types can be serialized, some types are serialized
in a different form such as strings) but doesn&#8217;t have pickle&#8217;s security issues.</p>
<p class="last">You select the serializer to be used by setting the <tt class="docutils literal"><span class="pre">SERIALIZER</span></tt> config item. (See the <a class="reference internal" href="config.html"><em>Configuring Pyro</em></a> chapter).
The range of valid choices is the name of the serializer from the list mentioned above.
The introduction of different serializers is a change that is <em>not</em> backwards compatible,
even if you change the setting back to &#8220;<tt class="docutils literal"><span class="pre">pickle</span></tt>&#8221;.</p>
</div>
</div>
<div class="section" id="proxies-connections-threads-and-cleaning-up">
<h2>Proxies, connections, threads and cleaning up<a class="headerlink" href="#proxies-connections-threads-and-cleaning-up" title="Permalink to this headline">¶</a></h2>
<p>Here are some rules:</p>
<ul>
<li><p class="first">Every single Proxy object will have its own socket connection to the daemon.</p>
</li>
<li><p class="first">You can share Proxy objects among threads, it will re-use the same socket connection.</p>
</li>
<li><p class="first">Usually every connection in the daemon has its own processing thread there, but for more details see the <a class="reference internal" href="servercode.html"><em>Servers: publishing objects</em></a> chapter.</p>
</li>
<li><p class="first">The connection will remain active for the lifetime of the proxy object.</p>
</li>
<li><p class="first">You can free resources by manually closing the proxy connection if you don&#8217;t need it anymore.
This can be done in two ways:</p>
<ol class="arabic">
<li><p class="first">calling <tt class="docutils literal"><span class="pre">_pyroRelease()</span></tt> on the proxy.</p>
</li>
<li><p class="first">using the proxy as a context manager in a <tt class="docutils literal"><span class="pre">with</span></tt> statement.
This ensures that when you&#8217;re done with it, or an error occurs (inside the with-block),
the connection is released:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">Proxy</span><span class="p">(</span><span class="s">&quot;.....&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">obj</span><span class="p">:</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">method</span><span class="p">()</span>
</pre></div>
</div>
</li>
</ol>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You can still use the proxy object when it is disconnected: Pyro will reconnect it as soon as it&#8217;s needed again.</p>
</div>
</li>
</ul>
</div>
<div class="section" id="oneway-calls">
<h2>Oneway calls<a class="headerlink" href="#oneway-calls" title="Permalink to this headline">¶</a></h2>
<p>Normal method calls always block until the response is returned. This can be a normal return value, <tt class="docutils literal"><span class="pre">None</span></tt>,
or an error in the form of a raised exception.</p>
<p>If you know that some methods never return any response or you are simply not interested in it (including
exceptions!) you can tell Pyro that certain methods of a proxy object are <em>one-way</em> calls:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">proxy</span><span class="o">.</span><span class="n">_pyroOneway</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s">&quot;someMethod&quot;</span><span class="p">)</span>
<span class="n">proxy</span><span class="o">.</span><span class="n">_pyroOneway</span><span class="o">.</span><span class="n">update</span><span class="p">([</span><span class="s">&quot;otherMethod&quot;</span><span class="p">,</span> <span class="s">&quot;processStuff&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>the <a class="reference internal" href="api/core.html#Pyro4.core.Proxy._pyroOneway" title="Pyro4.core.Proxy._pyroOneway"><tt class="xref py py-attr docutils literal"><span class="pre">Pyro4.core.Proxy._pyroOneway</span></tt></a> property is a set containing the names of the methods that
should be called as one-way (by default it is an empty set). For these methods, Pyro will not wait for a response
from the remote object. This means that your client program continues to
work, while the remote object is still busy processing the method call.
The return value of these calls is always <tt class="docutils literal"><span class="pre">None</span></tt>. You can&#8217;t tell if the method call
was successful, or if the method even exists on the remote object, because errors won&#8217;t be returned either!</p>
<p>See the <tt class="file docutils literal"><span class="pre">oneway</span></tt> example for more details.</p>
</div>
<div class="section" id="batched-calls">
<span id="id3"></span><h2>Batched calls<a class="headerlink" href="#batched-calls" title="Permalink to this headline">¶</a></h2>
<p>Doing many small remote method calls in sequence has a fair amount of latency and overhead.
Pyro provides a means to gather all these small calls and submit it as a single &#8216;batched call&#8217;.
When the server processed them all, you get back all results at once.
Depending on the size of the arguments, the network speed, and the amount of calls,
doing a batched call can be <em>much</em> faster than invoking every call by itself.
Note that this feature is only available for calls on the same proxy object.</p>
<p>How it works:</p>
<ol class="arabic simple">
<li>You create a batch proxy wrapper object for the proxy object.</li>
<li>Call all the methods you would normally call on the regular proxy, but use the batch proxy wrapper object instead.</li>
<li>Call the batch proxy object itself to obtain the generator with the results.</li>
</ol>
<p>You create a batch proxy wrapper using this: <tt class="docutils literal"><span class="pre">batch</span> <span class="pre">=</span> <span class="pre">Pyro4.batch(proxy)</span></tt> or this (equivalent): <tt class="docutils literal"><span class="pre">batch</span> <span class="pre">=</span> <span class="pre">proxy._pyroBatch()</span></tt>.
The signature of the batch proxy call is as follows:</p>
<dl class="method">
<dt id="batchproxy.__call__">
<tt class="descclassname">batchproxy.</tt><tt class="descname">__call__</tt><big>(</big><span class="optional">[</span><em>oneway=False</em>, <em>async=False</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#batchproxy.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p>Invoke the batch and when done, returns a generator that produces the results of every call, in order.
If <tt class="docutils literal"><span class="pre">oneway==True</span></tt>, perform the whole batch as one-way calls, and return <tt class="docutils literal"><span class="pre">None</span></tt> immediately.
If <tt class="docutils literal"><span class="pre">async==True</span></tt>, perform the batch asynchronously, and return an asynchronous call result object immediately.</p>
</dd></dl>

<p><strong>Simple example</strong>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">batch</span> <span class="o">=</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">batch</span><span class="p">(</span><span class="n">proxy</span><span class="p">)</span>
<span class="n">batch</span><span class="o">.</span><span class="n">method1</span><span class="p">()</span>
<span class="n">batch</span><span class="o">.</span><span class="n">method2</span><span class="p">()</span>
<span class="c"># more calls ...</span>
<span class="n">batch</span><span class="o">.</span><span class="n">methodN</span><span class="p">()</span>
<span class="n">results</span> <span class="o">=</span> <span class="n">batch</span><span class="p">()</span>   <span class="c"># execute the batch</span>
<span class="k">for</span> <span class="n">result</span> <span class="ow">in</span> <span class="n">results</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">result</span>   <span class="c"># process result in order of calls...</span>
</pre></div>
</div>
<p><strong>Oneway batch</strong>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">results</span> <span class="o">=</span> <span class="n">batch</span><span class="p">(</span><span class="n">oneway</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="c"># results==None</span>
</pre></div>
</div>
<p><strong>Asynchronous batch</strong></p>
<p>The result value of an asynchronous batch call is a special object. See <a class="reference internal" href="#async-calls"><em>Asynchronous (&#8216;future&#8217;) remote calls &amp; call chains</em></a> for more details about it.
This is some simple code doing an asynchronous batch:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">results</span> <span class="o">=</span> <span class="n">batch</span><span class="p">(</span><span class="n">async</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="c"># do some stuff... until you&#39;re ready and require the results of the async batch:</span>
<span class="k">for</span> <span class="n">result</span> <span class="ow">in</span> <span class="n">results</span><span class="o">.</span><span class="n">value</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">result</span>    <span class="c"># process the results</span>
</pre></div>
</div>
<p>See the <tt class="file docutils literal"><span class="pre">batchedcalls</span></tt> example for more details.</p>
</div>
<div class="section" id="asynchronous-future-remote-calls-call-chains">
<span id="async-calls"></span><h2>Asynchronous (&#8216;future&#8217;) remote calls &amp; call chains<a class="headerlink" href="#asynchronous-future-remote-calls-call-chains" title="Permalink to this headline">¶</a></h2>
<p>You can execute a remote method call and tell Pyro: &#8220;hey, I don&#8217;t need the results right now.
Go ahead and compute them, I&#8217;ll come back later once I need them&#8221;.
The call will be processed in the background and you can collect the results at a later time.
If the results are not yet available (because the call is <em>still</em> being processed) your code blocks
but only at the line you are actually retrieving the results. If they have become available in the
meantime, the code doesn&#8217;t block at all and can process the results immediately.
It is possible to define one or more callables (the &#8220;call chain&#8221;) that should be invoked
automatically by Pyro as soon as the result value becomes available.</p>
<p>You create an async proxy wrapper using this: <tt class="docutils literal"><span class="pre">async</span> <span class="pre">=</span> <span class="pre">Pyro4.async(proxy)</span></tt> or this (equivalent): <tt class="docutils literal"><span class="pre">async</span> <span class="pre">=</span> <span class="pre">proxy._pyroAsync()</span></tt>.
Every remote method call you make on the async proxy wrapper, returns a
<a class="reference internal" href="api/futures.html#Pyro4.futures.FutureResult" title="Pyro4.futures.FutureResult"><tt class="xref py py-class docutils literal"><span class="pre">Pyro4.futures.FutureResult</span></tt></a> object immediately.
This object means &#8216;the result of this will be available at some moment in the future&#8217; and has the following interface:</p>
<dl class="attribute">
<dt id="value">
<tt class="descname">value</tt><a class="headerlink" href="#value" title="Permalink to this definition">¶</a></dt>
<dd><p>This property contains the result value from the call.
If you read this and the value is not yet available, execution is halted until the value becomes available.
If it is already available you can read it as usual.</p>
</dd></dl>

<dl class="attribute">
<dt id="ready">
<tt class="descname">ready</tt><a class="headerlink" href="#ready" title="Permalink to this definition">¶</a></dt>
<dd><p>This property contains the readiness of the result value (<tt class="docutils literal"><span class="pre">True</span></tt> meaning that the value is available).</p>
</dd></dl>

<dl class="method">
<dt id="wait">
<tt class="descname">wait</tt><big>(</big><span class="optional">[</span><em>timeout=None</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Waits for the result value to become available, with optional wait timeout (in seconds). Default is None,
meaning infinite timeout. If the timeout expires before the result value is available, the call
will return <tt class="docutils literal"><span class="pre">False</span></tt>. If the value has become available, it will return <tt class="docutils literal"><span class="pre">True</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="then">
<tt class="descname">then</tt><big>(</big><em>callable</em><span class="optional">[</span>, <em>*args</em>, <em>**kwargs</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#then" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a callable to the call chain, to be invoked when the results become available.
The result of the current call will be used as the first argument for the next call.
Optional extra arguments can be provided via <tt class="docutils literal"><span class="pre">args</span></tt> and <tt class="docutils literal"><span class="pre">kwargs</span></tt>.</p>
</dd></dl>

<p>A simple piece of code showing an asynchronous method call:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">async</span> <span class="o">=</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">async</span><span class="p">(</span><span class="n">proxy</span><span class="p">)</span>
<span class="n">asyncresult</span> <span class="o">=</span> <span class="n">async</span><span class="o">.</span><span class="n">remotemethod</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&quot;value available?&quot;</span><span class="p">,</span> <span class="n">asyncresult</span><span class="o">.</span><span class="n">ready</span>
<span class="c"># ...do some other stuff...</span>
<span class="k">print</span> <span class="s">&quot;resultvalue=&quot;</span><span class="p">,</span> <span class="n">asyncresult</span><span class="o">.</span><span class="n">value</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#batched-calls"><em>Batched calls</em></a> can also be executed asynchronously.
Asynchronous calls are implemented using a background thread that waits for the results.
Callables from the call chain are invoked sequentially in this background thread.</p>
</div>
<p>See the <tt class="file docutils literal"><span class="pre">async</span></tt> example for more details and example code for call chains.</p>
<div class="section" id="async-calls-for-normal-callables-not-only-for-pyro-proxies">
<h3>Async calls for normal callables (not only for Pyro proxies)<a class="headerlink" href="#async-calls-for-normal-callables-not-only-for-pyro-proxies" title="Permalink to this headline">¶</a></h3>
<p>The async proxy wrapper discussed above is only available when you are dealing with Pyro proxies.
It provides a convenient syntax to call the methods on the proxy asynchronously.
For normal Python code it is sometimes useful to have a similar mechanism as well.
Pyro provides this too, see <a class="reference internal" href="tipstricks.html#future-functions"><em>Asynchronous (&#8216;future&#8217;) normal function calls</em></a> for more information.</p>
</div>
</div>
<div class="section" id="pyro-callbacks">
<h2>Pyro Callbacks<a class="headerlink" href="#pyro-callbacks" title="Permalink to this headline">¶</a></h2>
<p>Usually there is a nice separation between a server and a client.
But with some Pyro programs it is not that simple.
It isn&#8217;t weird for a Pyro object in a server somewhere to invoke a method call
on another Pyro object, that could even be running in the client program doing the initial call.
In this case the client program is a server itself as well.</p>
<p>These kinds of &#8216;reverse&#8217; calls are labeled <em>callbacks</em>. You have to do a bit of
work to make them possible, because normally, a client program is not running the required
code to also act as a Pyro server to accept incoming callback calls.</p>
<p>In fact, you have to start a Pyro daemon and register the callback Pyro objects in it,
just as if you were writing a server program.
Keep in mind though that you probably have to run the daemon&#8217;s request loop in its own
background thread. Or make heavy use of oneway method calls.
If you don&#8217;t, your client program won&#8217;t be able to process the callback requests because
it is by itself still waiting for results from the server.</p>
<p><strong>Exceptions in callback objects:</strong>
If your callback object raises an exception, Pyro will return that to the server doing the
callback. Depending on what that does with it, you might never see the actual exception,
let alone the stack trace. This is why Pyro provides a decorator that you can use
on the methods in your callback object in the client program: <tt class="docutils literal"><span class="pre">&#64;Pyro4.core.callback</span></tt>
(also available for convenience as <tt class="docutils literal"><span class="pre">&#64;Pyro4.callback</span></tt>).
This way, an exception in that method is not only returned to the caller, but also
raised again locally in your client program, so you can see it happen including the
stack trace:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Callback</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>

    <span class="nd">@Pyro4.callback</span>
    <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">&quot;callback received from server!&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="mi">1</span><span class="o">//</span><span class="mi">0</span>    <span class="c"># crash away</span>
</pre></div>
</div>
<p>See the <tt class="file docutils literal"><span class="pre">callback</span></tt> example for more details and code.</p>
</div>
<div class="section" id="miscellaneous-features">
<h2>Miscellaneous features<a class="headerlink" href="#miscellaneous-features" title="Permalink to this headline">¶</a></h2>
<p>Pyro provides a few miscellaneous features when dealing with remote method calls.
They are described in this section.</p>
<div class="section" id="error-handling">
<h3>Error handling<a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h3>
<p>You can just do exception handling as you would do when writing normal Python code.
However, Pyro provides a few extra features when dealing with errors that occurred in
remote objects. This subject is explained in detail its own chapter: <a class="reference internal" href="errors.html"><em>Errors and remote tracebacks</em></a>.</p>
<p>See the <tt class="file docutils literal"><span class="pre">exceptions</span></tt> example for more details.</p>
</div>
<div class="section" id="timeouts">
<h3>Timeouts<a class="headerlink" href="#timeouts" title="Permalink to this headline">¶</a></h3>
<p>Because calls on Pyro objects go over the network, you might encounter network related problems that you
don&#8217;t have when using normal objects. One possible problems is some sort of network hiccup
that makes your call unresponsive because the data never arrived at the server or the response never
arrived back to the caller.</p>
<p>By default, Pyro waits an indefinite amount of time for the call to return. You can choose to
configure a <em>timeout</em> however. This can be done globally (for all Pyro network related operations)
by setting the timeout config item:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Pyro4</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">COMMTIMEOUT</span> <span class="o">=</span> <span class="mf">1.5</span>      <span class="c"># 1.5 seconds</span>
</pre></div>
</div>
<p>You can also do this on a per-proxy basis by setting the timeout property on the proxy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">proxy</span><span class="o">.</span><span class="n">_pyroTimeout</span> <span class="o">=</span> <span class="mf">1.5</span>    <span class="c"># 1.5 seconds</span>
</pre></div>
</div>
<p>There is also a server setting related to oneway calls, that says if oneway method
calls should be executed in a separate thread or not. If this is set to <tt class="docutils literal"><span class="pre">False</span></tt>,
they will execute in</p>
<blockquote>
<div>Pyro4.config.ONEWAY_THREADED = True     # this is the default</div></blockquote>
<p>See the <tt class="file docutils literal"><span class="pre">timeout</span></tt> example for more details.</p>
</div>
<div class="section" id="automatic-reconnecting">
<h3>Automatic reconnecting<a class="headerlink" href="#automatic-reconnecting" title="Permalink to this headline">¶</a></h3>
<p>If your client program becomes disconnected to the server (because the server crashed for instance),
Pyro will raise a <a class="reference internal" href="api/errors.html#Pyro4.errors.ConnectionClosedError" title="Pyro4.errors.ConnectionClosedError"><tt class="xref py py-exc docutils literal"><span class="pre">Pyro4.errors.ConnectionClosedError</span></tt></a>.
It is possible to catch this and tell Pyro to attempt to reconnect to the server by calling
<tt class="docutils literal"><span class="pre">_pyroReconnect()</span></tt> on the proxy (it takes an optional argument: the number of attempts
to reconnect to the daemon. By default this is almost infinite). Once successful, you can resume operations
on the proxy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">proxy</span><span class="o">.</span><span class="n">method</span><span class="p">()</span>
<span class="k">except</span> <span class="n">Pyro4</span><span class="o">.</span><span class="n">errors</span><span class="o">.</span><span class="n">ConnectionClosedError</span><span class="p">:</span>
    <span class="c"># connection lost, try reconnecting</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">_pyroReconnect</span><span class="p">()</span>
</pre></div>
</div>
<p>This will only work if you take a few precautions in the server. Most importantly, if it crashed and comes
up again, it needs to publish its Pyro objects with the exact same URI as before (object id, hostname, daemon
port number).</p>
<p>See the <tt class="file docutils literal"><span class="pre">autoreconnect</span></tt> example for more details and some suggestions on how to do this.</p>
</div>
<div class="section" id="proxy-sharing">
<h3>Proxy sharing<a class="headerlink" href="#proxy-sharing" title="Permalink to this headline">¶</a></h3>
<p>Due to internal locking you can freely share proxies among threads.
The lock makes sure that only a single thread is actually using the proxy&#8217;s
communication channel at all times.
This can be convenient <em>but</em> it may not be the best way to approach things. The lock essentially
prevents parallelism. If you want calls to go in parallel, give each thread its own proxy.</p>
<p>Here are a couple of suggestions on how to make copies of a proxy:</p>
<ol class="arabic simple">
<li>use the <tt class="xref py py-mod docutils literal"><span class="pre">copy</span></tt> module, <tt class="docutils literal"><span class="pre">proxy2</span> <span class="pre">=</span> <span class="pre">copy.copy(proxy)</span></tt></li>
<li>create a new proxy from the uri of the old one: <tt class="docutils literal"><span class="pre">proxy2</span> <span class="pre">=</span> <span class="pre">Pyro4.Proxy(proxy._pyroUri)</span></tt></li>
<li>simply create a proxy in the thread itself (pass the uri to the thread instead of a proxy)</li>
</ol>
<p>See the <tt class="file docutils literal"><span class="pre">proxysharing</span></tt> example for more details.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="index.html">
              <img class="logo" src="_static/pyro.png" alt="Logo"/>
            </a></p>
  <h3><a href="index.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Clients: Calling remote objects</a><ul>
<li><a class="reference internal" href="#object-discovery">Object discovery</a></li>
<li><a class="reference internal" href="#calling-methods">Calling methods</a></li>
<li><a class="reference internal" href="#serialization">Serialization</a></li>
<li><a class="reference internal" href="#proxies-connections-threads-and-cleaning-up">Proxies, connections, threads and cleaning up</a></li>
<li><a class="reference internal" href="#oneway-calls">Oneway calls</a></li>
<li><a class="reference internal" href="#batched-calls">Batched calls</a></li>
<li><a class="reference internal" href="#asynchronous-future-remote-calls-call-chains">Asynchronous (&#8216;future&#8217;) remote calls &amp; call chains</a><ul>
<li><a class="reference internal" href="#async-calls-for-normal-callables-not-only-for-pyro-proxies">Async calls for normal callables (not only for Pyro proxies)</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pyro-callbacks">Pyro Callbacks</a></li>
<li><a class="reference internal" href="#miscellaneous-features">Miscellaneous features</a><ul>
<li><a class="reference internal" href="#error-handling">Error handling</a></li>
<li><a class="reference internal" href="#timeouts">Timeouts</a></li>
<li><a class="reference internal" href="#automatic-reconnecting">Automatic reconnecting</a></li>
<li><a class="reference internal" href="#proxy-sharing">Proxy sharing</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="commandline.html"
                        title="previous chapter">Command line tools</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="servercode.html"
                        title="next chapter">Servers: publishing objects</a></p>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="servercode.html" title="Servers: publishing objects"
             >next</a> |</li>
        <li class="right" >
          <a href="commandline.html" title="Command line tools"
             >previous</a> |</li>
        <li><a href="index.html">Pyro 4.21 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
        &copy; Copyright Irmen de Jong.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
    </div>
  </body>
</html>