PickleRPCServlet

Dict-RPC servlets.

class PickleRPCServlet.PickleRPCServlet

Bases: RPCServlet, SafeUnpickler

PickleRPCServlet is a base class for Dict-RPC servlets.

The “Pickle” refers to Python’s pickle module. This class is similar to XMLRPCServlet. By using Python pickles you get their convenience (assuming the client is Pythonic), but lose language independence. Some of us don’t mind that last one. ;-)

Conveniences over XML-RPC include the use of all of the following:

  • Any pickle-able Python type (datetime for example)

  • Python instances (aka objects)

  • None

  • Longs that are outside the 32-bit int boundaries

  • Keyword arguments

Pickles should also be faster than XML, especially now that we support binary pickling and compression.

To make your own PickleRPCServlet, create a subclass and implement a method which is then named in exposedMethods():

from PickleRPCServlet import PickleRPCServlet
class Math(PickleRPCServlet):
    def multiply(self, x, y):
        return x * y
    def exposedMethods(self):
        return ['multiply']

To make a PickleRPC call from another Python program, do this:

from MiscUtils.PickleRPC import Server
server = Server('http://localhost/Webware/Context/Math')
print(server.multiply(3, 4))     # 12
print(server.multiply('-', 10))  # ----------

If a request error is raised by the server, then MiscUtils.PickleRPC.RequestError is raised. If an unhandled exception is raised by the server, or the server response is malformed, then MiscUtils.PickleRPC.ResponseError (or one of its subclasses) is raised.

Tip: If you want callers of the RPC servlets to be able to introspect what methods are available, then include ‘exposedMethods’ in exposedMethods().

If you wanted the actual response dictionary for some reason:

print(server._request('multiply', 3, 4))
# {'value': 12, 'timeReceived': ...}

In which case, an exception is not purposefully raised if the dictionary contains one. Instead, examine the dictionary.

For the dictionary formats and more information see the docs for MiscUtils.PickleRPC.

__init__()

Subclasses must invoke super.

allowedGlobals()

Allowed class names.

Must return a list of (moduleName, klassName) tuples for all classes that you want to allow to be unpickled.

Example:

return [('datetime', 'date')]

Allows datetime.date instances to be unpickled.

awake(transaction)

Begin transaction.

call(methodName, *args, **keywords)

Call custom method.

Subclasses may override this class for custom handling of methods.

canBeReused()

Returns whether a single servlet instance can be reused.

The default is True, but subclasses con override to return False. Keep in mind that performance may seriously be degraded if instances can’t be reused. Also, there’s no known good reasons not to reuse an instance. Remember the awake() and sleep() methods are invoked for every transaction. But just in case, your servlet can refuse to be reused.

canBeThreaded()

Return whether the servlet can be multithreaded.

This value should not change during the lifetime of the object. The default implementation returns False. Note: This is not currently used.

close()
exposedMethods()

Get exposed methods.

Subclasses should return a list of methods that will be exposed through XML-RPC.

findGlobal(module, klass)

Find class name.

static handleException(transaction)

Handle exception.

If ReportRPCExceptionsInWebware is set to True, then flush the response (because we don’t want the standard HTML traceback to be appended to the response) and then handle the exception in the standard Webware way. This means logging it to the console, storing it in the error log, sending error email, etc. depending on the settings.

lastModified(_trans)

Get time of last modification.

Return this object’s Last-Modified time (as a float), or None (meaning don’t know or not applicable).

load(file)

Unpickle a file.

loads(s)

Unpickle a string.

log(message)

Log a message.

This can be invoked to print messages concerning the servlet. This is often used by self to relay important information back to developers.

name()

Return the name which is simple the name of the class.

Subclasses should not override this method. It is used for logging and debugging.

static notImplemented(trans)
open()
respond(transaction)

Respond to a request.

Invokes the appropriate respondToSomething() method depending on the type of request (e.g., GET, POST, PUT, …).

respondToHead(trans)

Respond to a HEAD request.

A correct but inefficient implementation.

respondToPost(trans)
resultForException(e, trans)

Get text for exception.

Given an unhandled exception, returns the string that should be sent back in the RPC response as controlled by the RPCExceptionReturn setting.

runMethodForTransaction(transaction, method, *args, **kw)
static runTransaction(transaction)
static sendOK(contentType, contents, trans, contentEncoding=None)

Send a 200 OK response with the given contents.

sendResponse(trans, response)

Timestamp the response dict and send it.

serverSidePath(path=None)

Return the filesystem path of the page on the server.

setFactory(factory)
sleep(transaction)

End transaction.

transaction()

Get the corresponding transaction.

Most uses of RPC will not need this.

static useBinaryPickle()

Determine whether binary pickling format shall be used.

When this returns True, the highest available binary pickling format will be used. Override this to return False to use the less-efficient text pickling format.