creating web API using JSON-RPC

7 views
Skip to first unread message

Ondrej Certik

unread,
Mar 26, 2010, 5:35:57 PM3/26/10
to sympy, sage-n...@googlegroups.com, femhub
Hi,

I made a few updates in my "login" branch of sympy gamma, and I've
implemented JSON-RPC web API to sympy, to get some idea how it works.

Try this:

git clone git://github.com/certik/sympy_gamma.git
cd sympy_gamma
git checkout -b login origin/login
cd tests
ipython

In [1]: import jsonrpclib

In [2]: s = jsonrpclib.SimpleServerProxy("http://2.latest.sympy-gamma.appspot.com/test-service/")

In [3]: s.eval_cell("2+3")
Out[3]: '5'

In [4]: s.eval_cell("""\
...: from sympy import sin, integrate, var
...: var("x")
...: integrate(sin(x), x)
...: """)
Out[4]: '-cos(x)'

In [5]: s.eval_cell("""\
...: from sympy import sin, integrate, var
...: var("x")
...: a = integrate(sin(x), x)
...: """)
Out[5]: ''

In [6]: s.eval_cell("a.diff(x)")
Out[6]: 'sin(x)'

In [7]: s.eval_cell("1/0")
Out[7]: 'Traceback (most recent call last):\n File
"/base/data/home/apps/sympy-gamma/2.340815556860663956/app/logic/utils.py",
line 32, in eval\n r = repr(eval(z, globals))\n File "", line 1,
in <module>\nZeroDivisionError: integer division or modulo by zero\n'

The notebook here:

http://2.latest.sympy-gamma.appspot.com/nb/

then uses the exact same interface, just implemented in pyjamas
(translated to javascript), that runs in your browser.

This API is currently very simple, in particular it doesn't allow
logins and thus it only remembers the Python namespace temporarily.
But it can be easily tested, see the tests in tests/test_jsonrpc.py,
e.g. here is an example:

def test_jsonrpc2():
s = jsonrpclib.SimpleServerProxy("http://localhost:8080/test-service/")
assert s.add(2, 3) == 5
assert s.add(2, 3) != "5"

assert s.add("2", "3") == "23"
assert s.add("2", "3") != 23
assert s.add("2", "3") != 5

where the add() method is implemented on the server as:

@jsonremote(testservice)
def add(response, a, b):
return a+b


So using this approach, I'll now try to create an API to worksheets
and logins and write tests for everything. That way, anyone can easily
use sympy (or femhub or anything else) in their web applications and
write clients that interface with this API. And then the web
notebook/online lab would be just another client.

I am CCing to the sage-notebook list. What do you think of this
approach? The tests in sagenb/testing/* seem to be using selenium and
testing the notebook including the javascript, right? E.g. it's
testing both the client (javascript) and the server (notebook). The
server part is implemented in sagenb/notebook/twist.py.

My motivation is to have some clean web API, that exposes the
functionality, so that it's easy for people to use it.

I have to see how it goes when I implement contexts (logins) etc.,
only then it could be compared. I'll keep you posted.

Ondrej

Reply all
Reply to author
Forward
0 new messages