Reputation: 14990
I am trying to understand JSON rpc in python.My http server looks as below.
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
def add(a, b):
"""Test function"""
return a + b
class RequestHandler(pyjsonrpc.HttpRequestHandler):
# Register public JSON-RPC methods
methods = {
"add": add
}
# Threading HTTP-Server
http_server = pyjsonrpc.ThreadingHttpServer(
server_address = ('localhost', 8080),
RequestHandlerClass = RequestHandler
)
print "Starting HTTP server ..."
print "URL: http://localhost:8080"
http_server.serve_forever()
My client looks as below.
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
http_client = pyjsonrpc.HttpClient(
url = "http://example.com/jsonrpc",
username = "Username",
password = "Password"
)
print http_client.call("add", 1, 2)
# Result: 3
# It is also possible to use the *method* name as *attribute* name.
print http_client.add(1, 2)
15 # Result: 3
I start http server as follows
'$ python http_server.py'
Starting HTTP server ...
URL: http://localhost:8080
Then I start client as follows
$ python http_client.py
I get the following error.
Traceback (most recent call last):
File "http_client.py", line 11, in <module>
print http_client.call("add", 1, 2)
File "/usr/local/lib/python2.7/dist-packages/pyjsonrpc/http.py", line 98, in call
password = self.password
File "/usr/local/lib/python2.7/dist-packages/pyjsonrpc/http.py", line 33, in http_request
response = urllib2.urlopen(request)
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 502: Bad Gateway
Upvotes: 0
Views: 830
Reputation: 1236
In the client script change your URL to localhost:8080 to match the server setup. Also you don't need a username or password for this simple implementation. I've included a working version of the client below.
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
http_client = pyjsonrpc.HttpClient(
url = "http://localhost:8080"
)
print http_client.call("add", 1, 2)
# Result: 3
# It is also possible to use the *method* name as *attribute* name.
print http_client.add(1, 2)
# Result: 3
Upvotes: 1