webservice服務器端實例代碼
# -*- coding utf-8 -*- #
import socket
import json
from spyne import Application, rpc, ServiceBase, Array, Integer, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
class CarConditionService(ServiceBase):
@rpc(Unicode, Integer, Integer, Unicode, _returns=Unicode)
def car_condition_price(ctx, rb_code, t, h, descs):
"""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
"""
print(rb_code, t, h, descs)
# price = getPrice(rb_code, t, h, desc)
price = 500000
data = {'code': 200, 'message': 'success', "data": {'price': price}}
return json.dumps(data)
application = Application([CarConditionService], 'spyne.examples.hello.soap',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
wsgi_application = WsgiApplication(application)
# wsgi_application.doc.wsdl11.build_interface_document("https://www.example.com/api")
if __name__ == '__main__':
import logging
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:8000")
logging.info("wsdl is at: http://localhost:8000/?wsdl")
hostname = socket.gethostname()
print(hostname)
server = make_server('0.0.0.0', 8000, wsgi_application)
server.serve_forever()
客戶端代碼:
# 需要安裝zeep
from requests import Session
from zeep import Client
from zeep.transports import Transport
# 這裏省略了一段代碼
session = Session() # 這裏是因爲url是https,不然不需要transport
session.verify = False
transport = Transport(session=session)
url = 'http://www.example.com/api?wsdl'
url = 'http://127.0.0.1:8000?wsdl'
client = Client(url, transport=transport)
result = client.service.car_condition_price('zhangsan', 1, 2, '1,45,56')
print(result)
訪問wsdl文檔如下:
遠程服務調用失敗,注意到location爲127.0.0.1。
故添加如下代碼設置location地址:
wsgi_application.doc.wsdl11.build_interface_document("https://www.example.com/api")
wsdl頁面變爲設置的域名:
遠程服務調用可以正常使用。