首页 > 解决方案 > 如何使用 spyne 将 Pandas 数据帧公开为 SOAP 服务?

问题描述

我想将Pandas数据框out_protocol=XmlDocument()作为SOAP Web 服务公开。

到目前为止,我只设法通过使用in_protocolString调用 Web 服务来公开 a 。这是工作代码。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。这是一个例子:

在此处输入图像描述

标签: pythonpandasspyne

解决方案


Soap Servicesxml固有地用于 Web 服务。从这个问题中,我收集到您需要xml向服务器提供数据!
正如您所说,您可以将转换result为 pandas DF,然后从 DF 转换为 xml, 链接

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)

推荐阅读