python 調用webservice接口

本文記錄自己的瞭解,如有錯誤,請各位大神指導

1.使用包suds

    pip install suds

2.直接上代碼

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

from suds.client import Client
from suds.transport.http import HttpAuthenticated

from suds.wsse import *



class Demo():

    def __init__(self, username, password, url_wsdl):
        self.username = username
        self.password = password
        self.url_wsdl = url_wsdl
        self.headers = {
            "Content-Type": "text/xml;charset=UTF-8",
            "SOAPAction": ""
        }

        transport = HttpAuthenticated(username=self.username, password=self.password)  #安全驗證所需用戶,密碼
        self.suds_client = Client(self.url_wsdl, timeout=5, transport=transport)
        
        try:
            security = Security()
            token = UsernameToken(self.username, self.password)
            token.setnonce()
            token.setcreated()
            security.tokens.append(token)
            self.suds_client.set_options(wsse=security)
            self.post_status = 200
        except Exception as e:
            self.post_status = 400
            self.suds_client = None

    def __send_post__(self, funcname="", ins={}, outs=[]):
        return self.__send_post_suds__(funcname=funcname, ins=ins, outs=outs)


    def __send_post_suds__(self,funcname="",ins={},outs=[]):
        try:
            func = getattr(self.suds_client.service,funcname)   # 是否有此方法
            resp_data = func(**ins)                             # 調用傳參
            self.post_status = 200
        except Exception,e:
            self.post_status = 400
            raise Exception("exception:"+str(e.message))
        
    def modify(self):
        try:
            ins = {
            }

            ret = self.__send_post__(funcname="modify", ins=ins, outs=["resultRetVal","resultInfo"])
            print(ret["resultInfo"])
            if ret["resultRetVal"] != "0":
                return "fail"
            else:
                return "success"
        except Exception as e:
            return e

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章