python jsonrpc错误坏网关

时间:2014-04-08 02:47:18

标签: python json http rpc json-rpc

我正在尝试理解python中的JSON rpc。我的http服务器如下所示。

#!/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()

我的客户端如下所示。

#!/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

我按如下方式启动http服务器

'$ python http_server.py'

Starting HTTP server ...
URL: http://localhost:8080

然后我按照以下方式启动客户端

$ python http_client.py

我收到以下错误。

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

1 个答案:

答案 0 :(得分:1)

在客户端脚本中,将您的URL更改为localhost:8080以匹配服务器设置。此简单实现也不需要用户名或密码。我在下面列出了一个工作版的客户端。

#!/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