python3.9.x发布webservice用于数据传输

WebService主要有三大要素:XML,SOAP和WSDL。采用XML格式封装,并增加了SOAP协议规定的的HTTP消息头,通过一个WSDL文件来说明自己有什么服务可以对外调用。适用于一些复杂数据类型的传输。

python3.9.8  pycharm2021.2.1

服务端:主要用到spyne包,简单明了,直接上代码

import json
from spyne import Application, rpc, ServiceBase, Iterable, Integer, Unicode, String
# 如果支持soap的协议需要用到Soap11
from spyne.protocol.soap import Soap11
# 可以创建一个wsgi服务器,做测试用
from spyne.server.wsgi import WsgiApplication



class HelloWorldService1(ServiceBase):
	# 输入和输出的类型,这里返回值是stringArray
    @rpc(Unicode, _returns=Unicode)
    def say_hello1(str, data):
        #str为传输的数据类型,data就是传输的数据,方法即为say_hello
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        # 写你的服务端对应的操作
        data1=json.loads(data,strict=False)
        # data1=data
        datasend.datasend(data1)
        #这里我用了另外一个程序datasend处理传过来的数据了
        return "ok"
application = Application([HelloWorldService1], 'http://schemas.xmlsoap.org/soap/envelope',
                          in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
wsgi_application = WsgiApplication(application)

if __name__ == '__main__':
    import logging
    # wsgiref是python内置的一个简单的、遵循wsgi接口的服务器。
    from wsgiref.simple_server import make_server
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
    logging.info("listening to http://127.0.0.1:8080")
    logging.info("wsdl is at: http://127.0.0.1:8080/?wsdl")
    # 127.0.0.1改成你的IP,让客户端所在电脑能访问就行
    server=make_server('127.0.0.1', 8080, wsgi_application)
    server.serve_forever()

客户端,这里注意不能直接pip install suds, 要pip install suds-py3才行,简易客户端:

# 基于suds_jurko做webservice客户端
from suds.client import Client
import json

if __name__ == '__main__':
    url = 'http://127.0.0.1:8080/?wsdl'
    #这个url地址就是服务端发布的那个
    client = Client(url)
    gg={
        "data1":"test",
        "Time1":"532498745",
        "data2":{
            "a1":"1111",
            "a2":"true"
        }
    }
    data=json.dumps(gg)

这是本人第一篇文,物联网数据相关,欢迎交流!

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>