spyne的json文档协议客户端是什么?

2 投票
2 回答
1051 浏览
提问于 2025-04-17 14:04

我正在尝试使用spyne的Hello World示例,基本的代码是:

class HelloWorldService(ServiceBase):
    @srpc(Unicode, Integer, _returns=Array(Unicode))
    def say_hello(name, times):
        for i in range(times):
            yield 'Hello, %s' % name

application = Application([HelloWorldService],
              tns='spyne.examples.hello',
              in_protocol=JsonDocument(validator='soft'),
              out_protocol=JsonDocument()
          )

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    wsgi_app = WsgiApplication(application)
    server = make_server('0.0.0.0', 7789, wsgi_app)
    print "rpc server start"
    server.serve_forever()

然后我想用requests库来连接它,代码是:

url = "http://127.0.0.1:7789/sayhello"
data = { "name": "World", "times": 4 }
headers = { 'content-type': 'application/json' }
r = requests.post(url, data=json.dumps(data), headers=headers)

但是返回的是404错误。

不过如果我使用HttpRpc协议,使用requests库就没问题。

所以我该如何实现一个客户端来使用Json Document协议呢?我更倾向于使用requests库。

2 个回答

1

我刚刚在 http://spyne.io 上添加了一个通过 JsonDocument 协议的请求示例。

可以看看这个链接: http://spyne.io/#inprot=JsonDocument&outprot=JsonDocument&s=rpc&tpt=WsgiApplication&validator=true

作为参考,你可以使用以下两种方式:

curl http://localhost:7789 -d '{ "say_hello" : { "name": "World", "times": 4 } }' 

或者

curl http://localhost:7789 -d '{ "say_hello" : ["World", 4]}' 

参数的顺序和 Python 端的参数顺序是一样的。

1

如果你想用JsonDocument作为协议,你需要用这种方式来发送数据...

data = { "say_hello" : { "name": "World", "times": 4 } }

这意味着你应该把你的函数名作为json的主要键,然后它的内容应该是一个包含你函数参数的json。

而你的网址应该保持不变,但不需要函数名,也就是说:

url = "http://127.0.0.1:7789/"

如果你想了解更多内容,可以去spyne的博客看看,地址是 http://spyne.io/blog/

撰写回答