12
2018
03

Python 创建与调用 SOAP webservice

安装 Python 3.6 与 PyCharm

 1. 调用 C# 的webservice 示例 , 这里是调用电商管易的api服务

# -*- coding: utf-8 -*-

from suds.client import Client
url = 'http://ip.ip.ip.ip:8095/Mobile_WS/GySyncService.asmx?WSDL'
client = Client(url)
#查看该service提供的方法
print(client)

#调用该service提供的GyStockClean方法, 简单参数 xs:string warehouse_code, xs:string type_code
try:
   result = client.service.GyStockClean('json', 'sign')
   print(result)
except WebFault as e:
  print(e)

#调用该service提供的GyLogisticsSync方法, 复杂实体类参数 ArrayOfGyLogisticsSyncModule
#传入 List<GyLogisticsSyncModule>  ->  ArrayOfGyLogisticsSyncModule
#返回 List<GyLogisticsSyncMsg>     ->  ArrayOfGyLogisticsSyncMsg
arrayLogistics = client.factory.create('ArrayOfGyLogisticsSyncModule')
print(arrayLogistics)

logistics = client.factory.create('GyLogisticsSyncModule')
print(logistics)

logistics.code = '001'
logistics.express_code = '001'
logistics.mail_no = '001'
logistics.operator_date = '2018-02-01'
arrayLogistics.GyLogisticsSyncModule.append(logistics)

logistics = {
    'code':'202',
    'express_code':'555',
    'mail_no':'1212',
    'operator_date':'2018-02-01'
}
arrayLogistics.GyLogisticsSyncModule.append(logistics)

result = client.service.GyLogisticsSync(arrayLogistics)
print(result)

返回结果

E:\Python\PycharmProjects\untitled\venv\Scripts\python.exe E:/Python/PycharmProjects/untitled/callC#WebService.py

Suds ( https://fedorahosted.org/suds/ )  version: 0.6

Service ( GySyncService ) tns="http://ifxtv.com/"
   Prefixes (1)
      ns0 = "http://ifxtv.com/"
   Ports (2):
      (GySyncServiceSoap)
         Methods (11):
            GyDeliverysGet(xs:string code, xs:string start_create, xs:string end_create, xs:int page_no, xs:int page_size, xs:string deliveryprint_begintime, xs:string deliveryprint_endtime, xs:string warehouse_code, xs:string shop_code, xs:string outer_code, xs:int print, xs:int scan, xs:int cod, xs:string vip_name, xs:int delivery)
            GyDeliverysUpdate(xs:string code, xs:string express_code, xs:string mail_no, ArrayOfDeliverysListModule list, xs:string weight_qty, xs:int page_no, xs:int page_size)
            GyLogisticsSync(ArrayOfGyLogisticsSyncModule list)
            GyPurchaseAdd(xs:string warehouse_code, xs:string supplier_code, xs:string order_type, ArrayOfDetail_listModule detail_list, xs:string type_code, xs:string purchase_code, xs:string ex_cost, xs:string note)
            GyStockAdd(xs:string warehouse_code, xs:string type_code, ArrayOfDetailsModule details, xs:string note, xs:string by1, xs:string by2)
            GyStockAdju(xs:string warehouse_code, xs:string order_type, ArrayOfDetailsModule details, xs:string note, xs:string operat, xs:string by1, xs:string by2)
            GyStockClean(xs:string warehouse_code, xs:string type_code)
            GyStockCountGet(xs:string start_create, xs:string end_create, xs:string start_operation, xs:string end_operation, xs:string warehouse_code, xs:string code, xs:string status, xs:string by1, xs:string by2)
            GyStockGet(xs:string warehouse_code, xs:string sku_code, xs:string item_code, xs:string by1, xs:string by2, xs:int page, xs:int page_size)
            GyStockSync(xs:string warehouse_code, xs:string type_code, ArrayOfDetailsModule details)
            GyVipIntegralSync(ArrayOfGyVipIntegralModule list)
         Types (34):
            ArrayOfDeliverys
            ArrayOfDeliverysListModule
            ArrayOfDetail_listModule
            ArrayOfDetails
            ArrayOfDetailsModule
            ArrayOfGyLogisticsSyncModule
            ArrayOfGyLogisticsSyncMsg
            ArrayOfGyVipIntegralModule
            ArrayOfInvoices
            ArrayOfStockCounts
            ArrayOfStockModule
            ArrayOfStockdetails
            GyDeliveryGetMsg
            GyDeliveryUpdateMsg
            GyLogisticsSyncModule
            GyLogisticsSyncMsg
            GyMsg
            GyPurchaseAddMsg
            GyStockAddMsg
            GyStockAdjuMsg
            GyStockCountGetMsg
            GyStockGetMsg
            GyVipIntegralModule
            GyVipIntegralMsg
            delivery_statusInfo
            deliverys
            deliverysListModule
            detail_listModule
            details
            detailsModule
            invoices
            stockCounts
            stockModule
            stockdetails
      (GySyncServiceSoap12)
         Methods (11):
            GyDeliverysGet(xs:string code, xs:string start_create, xs:string end_create, xs:int page_no, xs:int page_size, xs:string deliveryprint_begintime, xs:string deliveryprint_endtime, xs:string warehouse_code, xs:string shop_code, xs:string outer_code, xs:int print, xs:int scan, xs:int cod, xs:string vip_name, xs:int delivery)
            GyDeliverysUpdate(xs:string code, xs:string express_code, xs:string mail_no, ArrayOfDeliverysListModule list, xs:string weight_qty, xs:int page_no, xs:int page_size)
            GyLogisticsSync(ArrayOfGyLogisticsSyncModule list)
            GyPurchaseAdd(xs:string warehouse_code, xs:string supplier_code, xs:string order_type, ArrayOfDetail_listModule detail_list, xs:string type_code, xs:string purchase_code, xs:string ex_cost, xs:string note)
            GyStockAdd(xs:string warehouse_code, xs:string type_code, ArrayOfDetailsModule details, xs:string note, xs:string by1, xs:string by2)
            GyStockAdju(xs:string warehouse_code, xs:string order_type, ArrayOfDetailsModule details, xs:string note, xs:string operat, xs:string by1, xs:string by2)
            GyStockClean(xs:string warehouse_code, xs:string type_code)
            GyStockCountGet(xs:string start_create, xs:string end_create, xs:string start_operation, xs:string end_operation, xs:string warehouse_code, xs:string code, xs:string status, xs:string by1, xs:string by2)
            GyStockGet(xs:string warehouse_code, xs:string sku_code, xs:string item_code, xs:string by1, xs:string by2, xs:int page, xs:int page_size)
            GyStockSync(xs:string warehouse_code, xs:string type_code, ArrayOfDetailsModule details)
            GyVipIntegralSync(ArrayOfGyVipIntegralModule list)
         Types (34):
            ArrayOfDeliverys
            ArrayOfDeliverysListModule
            ArrayOfDetail_listModule
            ArrayOfDetails
            ArrayOfDetailsModule
            ArrayOfGyLogisticsSyncModule
            ArrayOfGyLogisticsSyncMsg
            ArrayOfGyVipIntegralModule
            ArrayOfInvoices
            ArrayOfStockCounts
            ArrayOfStockModule
            ArrayOfStockdetails
            GyDeliveryGetMsg
            GyDeliveryUpdateMsg
            GyLogisticsSyncModule
            GyLogisticsSyncMsg
            GyMsg
            GyPurchaseAddMsg
            GyStockAddMsg
            GyStockAdjuMsg
            GyStockCountGetMsg
            GyStockGetMsg
            GyVipIntegralModule
            GyVipIntegralMsg
            delivery_statusInfo
            deliverys
            deliverysListModule
            detail_listModule
            details
            detailsModule
            invoices
            stockCounts
            stockModule
            stockdetails


(GyStockAddMsg){
   success = False
   errorCode = "PARAM ERR"
   subErrorCode = None
   errorDesc = "盘点明细仓库代码[json]在管易系统中不存在"
   subErrorDesc = None
   requestMethod = "gy.erp.stock.count.add"
 }
(ArrayOfGyLogisticsSyncModule){
   GyLogisticsSyncModule[] = <empty>
 }
(GyLogisticsSyncModule){
   code = None
   express_code = None
   mail_no = None
   operator_date = None
 }
(ArrayOfGyLogisticsSyncMsg){
   GyLogisticsSyncMsg[] = 
      (GyLogisticsSyncMsg){
         success = False
         errorCode = "10001"
         errorDesc = "未找到对应管易物流代码"
         code = "001"
      },
      (GyLogisticsSyncMsg){
         success = False
         errorCode = "10001"
         errorDesc = "未找到对应管易物流代码"
         code = "202"
      },
 }

Process finished with exit code 0


2. 创建webservice 服务

    (1).python 2.7 soaplib 搭建方式

# -*- coding: UTF-8 -*-
import soaplib
from soaplib.core.util.wsgi_wrapper import run_twisted #发布服务
from soaplib.core.server import wsgi
from soaplib.core.service import DefinitionBase #所有服务类必须继承该类
from soaplib.core.service import soap #声明注解
from soaplib.core.model.clazz import Array #声明要使用的类型
from soaplib.core.model.clazz import ClassModel #若服务返回类,该返回类必须是该类的子类
from soaplib.core.model.primitive import Integer,String
class C_ProbeCdrModel(ClassModel):
     __namespace__ = "C_ProbeCdrModel"
     Name=String
     Id=Integer
class AdditionService(DefinitionBase):  #this is a web service      
     @soap(Integer,Integer,_returns=String)
     def addition(self,a,b):
        return str(a)+'+'+str(b)+'='+str(a+b)

     @soap(_returns=Array(String))
     def GetCdrArray(self):
        L_Result=["1","2","3"]
        return L_Result

     @soap(_returns=C_ProbeCdrModel)
     def GetCdr(self): #返回的是一个类,该类必须是ClassModel的子类,该类已经在上面定义
        L_Model=C_ProbeCdrModel()
        L_Model.Name=L_Model.Name
        L_Model.Id=L_Model.Id
        return L_Model

if __name__=='__main__':
    try:
        print('服务已经开启')
        from wsgiref.simple_server import make_server
        soap_application = soaplib.core.Application([AdditionService], 'tns')
        wsgi_application = wsgi.Application(soap_application)
        server = make_server('localhost', 7789, wsgi_application)
        server.serve_forever()
    except ImportError as e:
          print(e)


    (2).spyne 搭建方式 

#coding:utf-8

import sys,json
from spyne import Application, rpc, ServiceBase
from spyne import Integer,Iterable, String,Unicode,Array, ComplexModel
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from wsgiref.simple_server import make_server

class User(ComplexModel):
    name = Unicode
    sex = Unicode

class SomeSampleServices(ServiceBase):

    # 返回基本参数
    @rpc(String,String, _returns=String)
    def res_user(self, name, sex):
        return 'hello world,'+name+','+sex

    # 返回基本参数集合
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield 'Hello, %s' % name

    #返回实体类
    @rpc(Array(User), _returns=User)
    def make_user(self, user):
        print(user)
        tUser=User()
        tUser.name='TestNameReponse'
        tUser.sex='无'
        return  tUser

if __name__ == "__main__":
    soap_app = Application([SomeSampleServices],
                           'SampleServices',
                           in_protocol=Soap11(validator="lxml"),
                           out_protocol=Soap11())
    wsgi_app = WsgiApplication(soap_app)
    server = make_server('localhost', 8180, wsgi_app)

    sys.exit(server.serve_forever())

spyne 调用方式 

# -*- coding: utf-8 -*-

from suds.client import Client
url = 'http://localhost:8180/make_user?wsdl'
client = Client(url)
#查看该service提供的方法
print(client)

result = client.service.say_hello('json', 3)
print(result)

result = client.service.res_user('json', 'sign')
print(result)

users = client.factory.create("UserArray")
print(users)

user = client.factory.create("User")
user.name = "Test"
user.sex = "男"
users.User.append(user)

user2 = client.factory.create("User")
user2.name = "Test2"
user2.sex = "女"
users.User.append(user2)

result1 = client.service.make_user(users)
print(result1)

返回

E:\Python\PycharmProjects\untitled\venv\Scripts\python.exe E:/Python/PycharmProjects/untitled/soapwsClient.py

Suds ( https://fedorahosted.org/suds/ )  version: 0.6

Service ( SomeSampleServices ) tns="SampleServices"
   Prefixes (1)
      ns0 = "SampleServices"
   Ports (1):
      (Application)
         Methods (3):
            make_user(UserArray user)
            res_user(xs:string name, xs:string sex)
            say_hello(xs:string name, xs:integer times)
         Types (9):
            User
            UserArray
            make_user
            make_userResponse
            res_user
            res_userResponse
            say_hello
            say_helloResponse
            stringArray


(stringArray){
   string[] = 
      "Hello, json",
      "Hello, json",
      "Hello, json",
 }
hello world,json,sign
(UserArray){
   User[] = <empty>
 }
(User){
   name = "TestNameReponse"
   sex = "无"
 }

Process finished with exit code 0


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。