Using Pyjamas with bobo

This weekend i finally came around to connect Pyjamas to my bobo backend application through JSON-RPC. The following example shows all the code you need to enable JSON-RPC in the bobo backend.

Create a file ‘jsonrpc_application.py‘, the bobo backend application:

import bobo

I use lovely.jsonrpc for the JSON-RPC server implementation.

from lovely.jsonrpc.dispatcher import JSONRPCDispatcher

The PyjamasAPI class follows the JSONRPCExample that comes with the Pyjamas distibution. You may want to put your own remote API in here.

class PyjamasAPI(object):
    def echo(self, txt):
        return txt
    def reverse(self, txt):
        return txt[::-1]
    def uppercase(self, txt):
        return txt.upper()
    def lowercase(self, txt):
        return txt.lower()

Now create the jsonrpc dispatcher based on the provided API.

dispatcher = JSONRPCDispatcher(PyjamasAPI())

The next part is all that is needed to make the ‘bobo’ application process JSON-RPC calls.

Define a route, e.g. ‘/jsonrpc’ as the the service endpoint, configure it to return ‘application/json’ and let the dispatcher dispatch the request body. A check for the content type is necessary to get at the correct data from the WebOb request object. Pyjamas e.g. posts the JSON data in ‘x-www-form-urlencoded’ form.

@bobo.post('/jsonrpc', content_type='application/json')
def dispatch(bobo_request):
    content_type = bobo_request.headers['Content-Type']
    if content_type.startswith('application/x-www-form-urlencoded'):
        body = bobo_request.POST.items()[0][0]
    else:
        body = bobo_request.body
    return dispatcher.dispatch(body)

Thats all on the backend side.

In Pyjamas modify ‘examples/jsonrpc/JSONRPCExample.py’ and build it:

class EchoServicePython(JSONProxy):
    def __init__(self):
        JSONProxy.__init__(self, "http://localhost:8080/jsonrpc", \
        ["echo", "reverse", "uppercase", "lowercase"])

At last startup bobo. It is necessary to serve the JSONRPCExample from the bobo application (same domain) like static content:

$ bin/bobo -f jsonrpc_application.py \
           -s /demo=/path/to/examples/jsonrpc/output/

Now point your browser to

$ firefox http://localhost:8080/demo/JSONRPCExample.html

and run the example.

I hope you liked the walktrough. Btw, if you use the Google AppEngine template from my recent blogpost you can run the example almost unmodified from GAE too.

0 Responses to “Using Pyjamas with bobo”


  1. No Comments

Leave a Reply





Categories