簡體   English   中英

如何在SUDS中使用類型和方法

[英]How to use Types and Methods with SUDS

我的代碼通過SUDS連接到自動任務服務。 我得到了一個方法列表,我必須調用其中的一個。 我是新手,所以不確定如何正確執行此操作。 這是我的代碼,包括Bodsda的幫助:

import os, sys
import xml.etree.ElementTree as ET
from suds.client import Client
from suds.sax.element import Element


class Init():
    def __init__(self):
        #Search the app.config file for all data to be used
        script_dir = os.path.dirname(__file__)
        file_path = "app.config"
        abs_file_path = os.path.join(script_dir, file_path) 

        tree = ET.parse(abs_file_path)
        root = tree.getroot()
        sites = root.iter('AutotaskUpdateTicketEstimatedHours.My.MySettings')
        self.data = {}
        for site in sites: 
            apps = site.findall('setting')
            for app in apps:
                self.data[app.get('name')] = app.find('value').text


class ConnectATWS():
    def __init__(self):
        #Connect to server with the credentials
        app_config = Init()
        self.username = app_config.data["Username"]
        self.password = app_config.data["Password"]
        self.login_id = app_config.data["LoginID"]
        strQuery = """
        <queryxml>
            <entity>Ticket</entity>
            <query>
                <condition>
                    <field>Id
                        <expression op="GreaterThan">0</expression>
                    </field>
                </condition>
                <condition>
                    <field>Status
                        <expression op="NotEqual">5</expression>
                    </field>
                </condition>
                <condition>
                    <field>EstimatedHours
                        <expression op="IsNull"></expression>
                    </field>
                </condition>
            </query>
        </queryxml>"""
        new_url = 'https://webservices5.autotask.net/atservices/1.5/atws.wsdl'
        client = Client(new_url, username=self.login_id, password=self.password)
        response = client.service.query(strQuery)

        if response.ReturnCode != 1:
            print "Error code: %s" % response.ReturnCode
            print "Error response: %s" % response.Errors
            sys.exit(1)
        else:
            print "Query successful..."
            print "============================="
            print response.EntityResults



if __name__ == '__main__':
    handler = ConnectATWS()

這是我的回應:

(ATWSResponse){
   ReturnCode = 1
   EntityResults = ""
   EntityResultType = "ticket"
   Errors = ""
   EntityReturnInfoResults = ""
 }

這是我通過客戶端獲得的方法和類型的列表:

    Suds ( https://fedorahosted.org/suds/ )  version: 0.4 GA  build: R699-20100913

Service ( ATWS ) tns="http://autotask.net/ATWS/v1_5/"
   Prefixes (1)
      ns0 = "http://autotask.net/ATWS/v1_5/"
   Ports (1):
      (ATWSSoap)
         Methods (14):
            CreateAttachment(Attachment attachment, )
            DeleteAttachment(xs:long attachmentId, )
            GetAttachment(xs:long attachmentId, )
            GetFieldInfo(xs:string psObjectType, )
            GetInvoiceMarkup(xs:int InvoiceId, xs:string Format, )
            GetWsdlVersion()
            create(ArrayOfEntity Entities, )
            delete(ArrayOfEntity Entities, )
            getEntityInfo()
            getThresholdAndUsageInfo()
            getUDFInfo(xs:string psTable, )
            getZoneInfo(xs:string UserName, )
            query(xs:string sXML, )
            update(ArrayOfEntity Entities, )
         Types (108):
            ATWSError
            ATWSResponse
            ATWSZoneInfo
            Account
            AccountLocation
            AccountNote
            AccountTeam
            AccountToDo
            ActionType
            AdditionalInvoiceFieldValue
            AllocationCode
            Appointment
            ArrayOfATWSError
            ArrayOfEntity
            ArrayOfEntityInfo
            ArrayOfEntityReturnInfo
            ArrayOfField
            ArrayOfPickListValue
            ArrayOfUserDefinedField
            Attachment
            AttachmentInfo
            AutotaskIntegrations
            BillingItem
            BillingItemApprovalLevel
            ChangeRequestLink
            ClientPortalUser
            Contact
            Contract
            ContractBlock
            ContractCost
            ContractFactor
            ContractMilestone
            ContractNote
            ContractRate
            ContractRetainer
            ContractService
            ContractServiceAdjustment
            ContractServiceBundle
            ContractServiceBundleAdjustment
            ContractServiceBundleUnit
            ContractServiceUnit
            ContractTicketPurchase
            Country
            Department
            Entity
            EntityDuplicateStatus
            EntityInfo
            EntityReturnInfo
            EntityReturnInfoDatabaseAction
            ExpenseItem
            ExpenseReport
            Field
            InstalledProduct
            InstalledProductType
            InstalledProductTypeUdfAssociation
            InternalLocation
            InventoryItem
            InventoryItemSerialNumber
            InventoryLocation
            InventoryTransfer
            Invoice
            InvoiceTemplate
            Opportunity
            PaymentTerm
            Phase
            PickListValue
            Product
            ProductVendor
            Project
            ProjectCost
            ProjectNote
            PurchaseOrder
            PurchaseOrderItem
            PurchaseOrderReceive
            Quote
            QuoteItem
            QuoteLocation
            Resource
            ResourceRole
            ResourceSkill
            Role
            SalesOrder
            Service
            ServiceBundle
            ServiceBundleService
            ServiceCall
            ServiceCallTask
            ServiceCallTaskResource
            ServiceCallTicket
            ServiceCallTicketResource
            ShippingType
            Skill
            Task
            TaskNote
            TaskPredecessor
            TaskSecondaryResource
            Tax
            TaxCategory
            TaxRegion
            Ticket
            TicketChangeRequestApproval
            TicketCost
            TicketNote
            TicketSecondaryResource
            TimeEntry
            UserDefinedField
            UserDefinedFieldDefinition
            UserDefinedFieldListItem

我需要使用ATWSResponse類型,但我不太了解如何執行此操作。 此外,我正在嘗試模擬此vb.net代碼部分,該部分將執行我在Python中嘗試執行的操作:

Sub ProcessTicket()
    Dim boolQueryFinished = False
    Dim strCurrentID As String = "0"
    Dim strQuery As String
    Dim strCriteria As String = ""
    Dim TicketArray(0) As Ticket

    While (Not (boolQueryFinished))
        If LCase(Trim(varIgnoreTicketStatus)) = "true" Then
            WriteToLog("Updating All Tickets Where EstimatedHours Is Null")
        Else
            WriteToLog("Updating Ticket Where Status <> Complete And EstimatedHours Is Null")
            ' 5 - Complete
            strCriteria = "<condition><field>Status<expression op=""NotEqual"">5</expression></field></condition>"
        End If

        strQuery = "<queryxml><entity>Ticket</entity><query>" & _
                    "<condition><field>id<expression op=""greaterthan"">" & strCurrentID & "</expression></field></condition>" & strCriteria & _
                    "<condition><field>EstimatedHours<expression op=""isnull""></expression></field></condition>" & _
                    "</query></queryxml>"

        Dim r As ATWSResponse
        Dim strLog As String

        r = ATWSService.query(strQuery)
        WriteToLog("Found " & r.EntityResults.Length & " Tickets begining at " & strCurrentID)

        If r.EntityResults.Length > 0 Then
            For Each ent As Entity In r.EntityResults
                CType(ent, Ticket).EstimatedHours = EstHoursDefault

                TicketArray(0) = CType(ent, Ticket)

                Dim sResponse As ATWSResponse
                Dim entityArray() As Entity = CType(TicketArray, Entity())
                sResponse = ATWSService.update(entityArray)

我的問題是如何使用我的Python代碼成功查詢QueryXML並返回vb.net代碼中的實體?

首先,用於連接api的網址不是正確的網址。 我需要使用https://webservices5.autotask.net/atservices/1.5/atws.wsdl

客戶端收到響應后,我必須匹配ReturnCode才能運行所需的代碼。 返回碼不能為1(這是查詢中的錯誤),因此我使用了:

        if response.ReturnCode != 1:
            print "Error code: %s" % response.ReturnCode
            print "Error response: %s" % response.Errors
            sys.exit(1)
        else:
            print "Query successful..."
            print "============================="
            response = response.EntityResults[0]

為了存儲返回的數據(實體),即工單,我必須執行以下循環:

            entities = []
            for entity in response:
                entities.append(dict(entity))

            for entity in entities:
                self.query_data.append(entity["Title"] + "  Estimated Hours " + str(entity["EstimatedHours"]))

這樣,我可以將元組列表存儲在實體列表中,以便隨后訪問每個實體。 完成此操作后,我要做的就是將結果追加到列表self.query_data

注意:感謝Bodsda提供的幫助,幫助我弄清楚我是如何使用XML查詢錯誤的地址的,以及有關循環的幫助。

我不確定,但是除了cpburnz做出的回答外,我注意到在似乎有效的vb代碼中,應該像在vb中創建一個名為ATWSService的對象的客戶端那樣,將python變量r創建為ATWSResponse。 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM