如何使用spyne将Pandas数据帧公开为SOAP服务?

时间:2019-06-18 13:23:27

标签: python pandas spyne

我想使用out_protocol=XmlDocument()作为 SOAP 网络服务公开 Pandas 数据框。

到目前为止,我只能通过使用String in_protocol 调用Web服务来公开HTTP。这是工作代码。

服务器代码:

from spyne import Application, srpc, ServiceBase, \
    Integer, Unicode, String

from spyne import Iterable
from spyne.protocol.http import HttpRpc
from spyne.protocol.soap import Soap11
from spyne.protocol.json import JsonDocument
from spyne.protocol.xml import XmlDocument

from spyne.server.wsgi import WsgiApplication

class HelloWorldService(ServiceBase):
    @srpc(String, Integer, _returns=String)
    def say_hello(name, times):
        s = ('Hi' + str(name)+' ')*times
        return s

application = Application([HelloWorldService],
    tns='spyne.examples.hello.http',
    in_protocol=HttpRpc(),    #Soap11 for SOAP client
    out_protocol=XmlDocument()
)
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    wsgi_app = WsgiApplication(application)
    server = make_server('127.0.0.1', 8000, wsgi_app)
    server.serve_forever()

客户代码:

curl "http://localhost:8000/say_hello?times=5&name=Dave"

如何更改代码以最好地公开Pandas数据框而不是字符串。以及如何使客户端使用SOAP协议发出请求?

我对SOAP客户端的尝试:

from zeep import Client

client = Client('http://localhost:8000/?wsdl')
result = client.service.say_hello("Antonio", 10)

print(result)

Web服务的预期输出应为类似表格的xml。这是一个示例:

enter image description here

1 个答案:

答案 0 :(得分:1)

Soap Services本质上将xml用于Web服务。通过这个问题,我认为您需要xml才能馈送给服务器!
如您所说,您可以将result转换为熊猫DF,然后从DF转换为xml,link

def to_xml(df, filename=None, mode='w'):
    def row_to_xml(row):
        xml = ['<item>']
        for i, col_name in enumerate(row.index):
            xml.append('  <field name="{0}">{1}</field>'.format(col_name, row.iloc[i]))
        xml.append('</item>')
        return '\n'.join(xml)
    res = '\n'.join(df.apply(row_to_xml, axis=1))

    if filename is None:
        return res
    with open(filename, mode) as f:
        f.write(res)
相关问题