marco.pantaleoni@gmail.com | My favorites | Profile | Sign out
Project Home Downloads Wiki Issues Source
Search
for
Updated Jun 27, 2010 by luke.leighton
  PyjamasWithCherryPyJSONRPC  
Pyjamas with CherryPy JSONRPC

Wiki has Moved

The Pyjamas Wiki is now at http://pyjs.org/wiki

JSON-RPC with pyjamas and cherrypy

The following has been tested with pyjamas 0.6 and cherrypy 3.1. Pyjamas contains an example client in .../examples/jsonrpc. You can easily test this example with the following cherrypy script:

import cherrypy
import json
import os

PYJSDIR
='...'

def jsonrpchdl():
 
print "before_handler jsonrpc"
 
# note: wheter req.body is a string or file depends on the content-type!
  req
= cherrypy.request
 
try: size = int(req.headers["Content-Length"])
 
except: size = 1
 
try:
    json_string
= req.body.read()
   
print "json_string [%s]" % json_string
   
#key = req.params.keys()[0]
    obj
= json.loads(json_string)
   
#log("obj %s" % obj);
    myparams
= {}
   
for key, val in obj.items():
      mykey
= str(key)
      myparams
[mykey] = val
    req
.params = myparams
 
except: pass
cherrypy
.tools.jsonrpchdl = cherrypy.Tool('before_handler',jsonrpchdl)

class Root:
 
@cherrypy.expose
 
def default(self,*args):
    fname
= os.path.join(PYJSDIR,args[0])
   
print "try to return contents of file %s" % fname
    f
= file(fname)
    s
= f.read()
   
return s

 
@cherrypy.expose
 
@cherrypy.tools.jsonrpchdl()
 
def services(self, *args, **kwargs):
   
print "echo service"
   
print args
   
print kwargs
    method
= kwargs['method']
    f
= getattr(self,method)
    res
= f(kwargs['params'][0])
   
return json.dumps({'id':kwargs['id'],'result':res,'error':None})
 
def echo(self, text):
   
return text
 
def reverse(self, text):
   
return text[::-1]
 
def uppercase(self, text):
   
return text.upper()
 
def lowercase(self,text):
   
return text.lower()

if __name__ == "__main__":
  cherrypy
.quickstart(Root(),"/",
             
{'global':{'server.socket_port':9000,'log.screen':True}})

The variable PYJSDIR should contain the absolute path to your .../examples/jsonrpc/output directory. Now start this script and open http://127.0.0.1:9000/JSONRPCExample.html in your browser. The Send to Python Service button should work as desired.

Lets have a deeper look at this script.

The first method jsonrpchdl is later used as a 'before_handler', ie. it called by cherrypy before cherrypy calls our page handler. It reads the json string from the message body and creates the appropriate keyword args used later in our page handler. The line

cherrypy.tools.jsonrpchdl = cherrypy.Tool('before_handler',jsonrpchdl)

registers the handler within cherrypy.

Now follows the published class Root. It contains two exposed methods: default works as a default handler, ie. its called by cherrypy if there is no other exposed method which could handle the requested url. We use this method to deliver the static pages (its just to keep the example small, its of course not intended to be used in real code!). The most interesting method in our case is services, which has both the expose and the jsonrpc decorators. The kwargs array contains our json parameters. This method just uses getattr to forward the request to the right method and returns a json result. The latter methods implement the functions used in the pyjamas client.

Enter a comment:


show hide Wiki markup help
=Heading1=
==Heading2==
===Heading3===

*bold*     _italic_
`inline code`
escape: `*`

Indent lists 2 spaces:
  * bullet item
  # numbered list

{{{
verbatim code block
}}}

Horizontal rule
----

WikiWordLink
[http://domain/page label]
http://domain/page

|| table || cells ||

More examples
Powered by Google Project Hosting