【问题标题】:How to expose Pandas data frame as SOAP service using spyne?如何使用 spyne 将 Pandas 数据帧公开为 SOAP 服务?
【发布时间】:2019-06-18 13:23:27
【问题描述】:

我想将带有 out_protocol=XmlDocument()Pandas 数据框公开为 SOAP 网络服务。

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

服务器代码:

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。这是一个例子:

【问题讨论】:

  • 什么是熊猫数据框?预期的 XML 输出是什么?
  • 您好,pandas 数据框本质上是一种数据结构,其组成类似于具有行和列的数据库表。你可以在这里查看:geeksforgeeks.org/python-pandas-dataframe。我添加了所需输出的示例。

标签: python pandas spyne


【解决方案1】:

Soap 服务使用 xml 固有地用于 Web 服务。从这个问题中,我了解到您需要 xml 来提供给服务器!!
正如您所说,您可以将result 转换为pandas 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)

【讨论】:

  • 很好,我正在考虑这样的事情。您能否发布网络服务的代码以确保完整性?
  • 我没有您正在使用的文档。所以,我不确定它是否对你有帮助。
  • 您可以只使用示例数据框。例如:my_df = pd.DataFrame(data=[4,5,6,7], index=range(0,4), columns=['A'])
猜你喜欢
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多