python jsonrpc错误:网关错误

0 投票
1 回答
812 浏览
提问于 2025-04-18 01:48

我正在尝试理解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 个回答

1

在客户端脚本中,把你的网址改成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

撰写回答