09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 18 ■ RPC<br />

8.0<br />

<br />

<br />

<br />

<br />

If this response looks a bit verbose for the amount <strong>of</strong> data that it is transmitting, then you will be<br />

happy to learn about the RPC mechanism that we tackle next.<br />

JSON-RPC<br />

The bright idea behind JSON is to serialize data structures to strings that use the syntax <strong>of</strong> the JavaScript<br />

programming language. This means that JSON strings can be turned back into data in a web browser<br />

simply by using the eval() function. By using a syntax specifically designed for data rather than adapting<br />

a verbose document markup language like XML, this remote procedure call mechanism can make your<br />

data much more compact while simultaneously simplifying your parsers and library code.<br />

Purpose: Remote procedure calls<br />

Standard: http://json-rpc.org/wiki/specification<br />

Runs atop: HTTP<br />

THE JSON-RPC PROTOCOL<br />

Data types: int; float; unicode; list; dict with unicode keys; None<br />

Libraries: many third-party, including lovely.jsonrpc<br />

JSON-RPC is not supported in the <strong>Python</strong> Standard Library (at least at the time <strong>of</strong> writing), so you<br />

will have to choose one <strong>of</strong> the several third-party distributions available. You can find these distributions<br />

on the <strong>Python</strong> Package Index. My own favorite is lovely.jsonrpc, contributed to the <strong>Python</strong> community<br />

by Lovely Systems GmBH in Austria. If you install it in a virtual environment (see Chapter 1), then you<br />

can try out the server and client shown in Listings 18–5 and 18–6.<br />

Listing 18–5. A JSON-RPC Server<br />

#!/usr/bin/env python<br />

# <strong>Foundations</strong> <strong>of</strong> <strong>Python</strong> <strong>Network</strong> <strong>Programming</strong> - Chapter 18 - jsonrpc_server.py<br />

# JSON-RPC server<br />

from wsgiref.simple_server import make_server<br />

import lovely.jsonrpc.dispatcher, lovely.jsonrpc.wsgi<br />

def lengths(*args):<br />

» results = []<br />

» for arg in args:<br />

» » try:<br />

» » » arglen = len(arg)<br />

» » except TypeError:<br />

» » » arglen = None<br />

» » results.append((arglen, arg))<br />

» return results<br />

313

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!