python - 带有请求客户端的 jsonrpc 服务器

标签 python twisted

尝试通过 requests.post() 请求联系 txjsonrpc 服务器。

服务器

from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor


class JsonRpc(jsonrpc.JSONRPC):
    def jsonrpc_status(self):
        return {"status": "200"}

reactor.listenTCP(interface="127.0.0.1", port=7081, factory=server.Site(JsonRpc()))
reactor.run()

客户端

curl -X POST http://127.0.0.1:7081 -d '{"params": [], "method": "status"}'
>>> '{"status": 200}'

这有效。

Python 库请求没有:

客户#2

import requests

req = requests.post(
    url="http://127.0.0.1:7081",
    data={
        "params": [],
        "method": "status"
    })

print req.status_code
>>> 500

服务器发出错误:

  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
exceptions.ValueError: No JSON object could be decoded

requests.post(data) 的参数在客户端 #2 示例中是正确的。但是,如果我查看 ngrep 输出,我可以看到 params 被丢弃。

CSI:ngrep

bla@bla:$ sudo ngrep -qt -W byline port 7081
interface: eth0 (192.168.1.0/255.255.255.0)
filter: (ip or ip6) and ( port 7081 )

T 2015/08/30 16:03:18.202439 192.168.1.30:41272 -> 192.168.1.61:7081 [AP]
POST / HTTP/1.1.
Host: 192.168.1.61:7081.
Content-Length: 13.
Content-Type: application/x-www-form-urlencoded.
Accept-Encoding: gzip, deflate, compress.
Accept: */*.
User-Agent: Mozilla 4.3.
.
method=status

如您所见,仅传输了method=status。 requests 决定我的 params 参数不值得发送,因为它是空的。这会在 txjsonrpc 服务器上创建一个异常。

如何通过 requests 客户端请求联系 txjsonrpc 服务器?

还有;我不介意切换到另一个与 Twisted 兼容的 jsonrpc 服务器库,如果这会让我的生活更轻松的话。

最佳答案

另请注意,来自 requests 的 POST 并未像 curl -d 那样发送 JSON,而是发送 x-www-form-urlencoded 键/值对。尝试在 requests.post 调用中将 data= 替换为 json=,如 this example 所示.

关于python - 带有请求客户端的 jsonrpc 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32297742/

相关文章:

循环200到205的Python整数

python - 在 requirements.txt 中打包所有依赖项

python - 如何使用 Selenium - Python 选择下拉菜单选项值

python - 从 PyInstaller 包访问 Python 解释器

python - Web 服务中的 Twisted 延迟与阻塞

python - 有什么好方法对时间序列股票数据进行分组吗?

python - 在 Django 1.10 中使用 Postgres 搜索时出现 NotImplementedError

twisted - 使用 Pypy 运行 twind

python - Twisted 的服务间消息传递/总线

python - 扭曲的海螺文件传输