2014-02-05 4 views
0

I am a complete Python noob 이제 foreshadowing이 완료되었으므로 SOAP 응답에서 일부 정보를 구문 분석하려고합니다.올바른 응답을받지 못하는 이유는 무엇입니까?

<soap:Body> 
    <ProcessMessageResponse xmlns="http://www.starstandards.org/webservices/2005/10/transport"> 
    <payload> 
     <content id="Content0"> 
      <CustomerLookupResponse xmlns=""> 
       <Customer> 
       <CompanyNumber>ZQ1</CompanyNumber> 
       <CustomerNumber>1051012</CustomerNumber> 
       <TypeCode>I</TypeCode> 
       <LastName>NAME</LastName> 
       <FirstName>BASIC</FirstName> 
       <MiddleName/> 
       <Salutation/> 
       <Gender/> 
       <Language/> 
       <Address1/> 
       <Address2/> 
       <Address3/> 
       <City/> 
       <County/> 
       <StateCode/> 
       <ZipCode>0</ZipCode> 
       <PhoneNumber>0</PhoneNumber> 
       <BusinessPhone>0</BusinessPhone> 
       <BusinessExt>0</BusinessExt> 
       <FaxNumber>0</FaxNumber> 
       <BirthDate>0</BirthDate> 
       <DriversLicense/> 
       <Contact/> 
       <PreferredContact/> 
       <MailCode/> 
       <TaxExmptNumber/> 
       <AssignedSalesperson/> 
       <CustomerType/> 
       <PreferredPhone/> 
       <CellPhone>0</CellPhone> 
       <PagePhone>0</PagePhone> 
       <OtherPhone>0</OtherPhone> 
       <OtherPhoneDesc/> 
       <Email1/> 
       <Email2/> 
       <OptionalField/> 
       <AllowContactByPostal/> 
       <AllowContactByPhone/> 
       <AllowContactByEmail/> 
       <BusinessPhoneExtension/> 
       <InternationalBusinessPhone/> 
       <InternationalCellPhone/> 
       <ExternalCrossReferenceKey>0</ExternalCrossReferenceKey> 
       <InternationalFaxNumber/> 
       <InternationalOtherPhone/> 
       <InternationalHomePhone/> 
       <CustomerPreferredName/> 
       <InternationalPagerPhone/> 
       <PreferredLanguage/> 
       <LastChangeDate>20130401</LastChangeDate> 
       <Vehicles/> 
       <CCID/> 
       <CCCD>0</CCCD> 
       </Customer> 
      </CustomerLookupResponse> 
     </content> 
    </payload> 
    </ProcessMessageResponse> 
</soap:Body> 

나는 내가 원하는 응답 구문 분석하기 위해 무엇을했는지 보여주기 위해 다음과 같은 코드를 가지고 : 리스폰스의 몸은 아래와 같습니다 내가 확실하지 오전

customer_number = '' 
customer_first_name = '' 
customer_last_name = '' 

def send_customer_lookup(data): 
    soap_action = 'http://www.starstandards.org/webservices/2005/10/transport/operations/ProcessMessage' 
source_port = random.randint(6000, 20000) 
    webservice = httplib.HTTPSConnection('otqa.arkona.com', source_address=('', source_port)) 
    webservice.putrequest('POST', '/OpenTrack/Webservice.asmx?wsdl') 
    webservice.putheader('User-Agent', 'OpenTrack-Heartbeat') 
    webservice.putheader('Content-Type', 'application/soap+xml') 
    webservice.putheader('Content-Length', '%d' % len(data)) 
    webservice.putheader('SOAPAction', soap_action) 
    webservice.endheaders() 
    webservice.send(data) 
    response = webservice.getresponse() 
    response_xml = str(response.read()) 

    doc = ET.fromstring(response_xml) 
    for customer in doc.findall('.//{http://www.starstandards.org/webservices/2005/10/transport}Payload'): 
     global customer_number 
     global customer_first_name 
     global customer_last_name 
     customer_number = customer.findtext('{http://www.starstandards.org/webservices/2005/10/transport}CustomerNumber') 
     customer_first_name = customer.findtext('{http://www.starstandards.org/webservices/2005/10/transport}FirstName') 
     customer_last_name = customer.findtext('{http://www.starstandards.org/webservices/2005/10/transport}LastName') 

    webservice.close() 
    return customer_number, customer_first_name, customer_last_name, response_xml 

을 이유를 출력이 ' ', ' ', ' ', <xml response>...

+0

(안 대답하지만) 그 webservice.putrequest 물건 리터의 많은 그것과 같은 ooks는 일반적인 send_soap_request() 함수로 추상화되어야합니다. –

+0

@HughBothwell 고맙습니다. 지금 당장은 작동하는 것을 필요로합니다. – DarthOpto

답변

1

과 같이 나타납니다. 필드 이름을 지나치게 지정하는 것으로 보이므로 일치하지 않으므로 for customer in ...이 실행되지 않습니다. 이것을 시도하십시오 :

import httplib 
import xml.etree.ElementTree as ET 

def send_customer_lookup(data): 
    soap_action = 'http://www.starstandards.org/webservices/2005/10/transport/operations/ProcessMessage' 
    source_port = random.randint(6000, 20000) 
    with httplib.HTTPSConnection('otqa.arkona.com', source_address=('', source_port)) as webservice: 
     webservice.putrequest('POST', '/OpenTrack/Webservice.asmx?wsdl') 
     webservice.putheader('User-Agent', 'OpenTrack-Heartbeat') 
     webservice.putheader('Content-Type', 'application/soap+xml') 
     webservice.putheader('Content-Length', '%d' % len(data)) 
     webservice.putheader('SOAPAction', soap_action) 
     webservice.endheaders() 
     webservice.send(data) 
     response_xml = str(webservice.getresponse().read()) 

    doc = ET.fromstring(response_xml) 
    results = [] 
    for customer in doc.findall('.//CustomerLookupResponse/'): 
     customer_number  = customer.findtext('CustomerNumber') 
     customer_first_name = customer.findtext('FirstName') 
     customer_last_name = customer.findtext('LastName') 
     results.append((customer_number, customer_first_name, customer_last_name)) 

    return results 

일반적으로 전역 변수 이름은 악의적입니다. 나는 당신이 '변수가 정의되지 않은'오류를 얻고 있기 때문에 그들을 추가했다고 추정한다. 그건 for-loop가 실제로 돌아 가지 않는다는 단서 였을 것입니다.

+0

고맙습니다. 이것은 대단히 도움이되었습니다. – DarthOpto

0

당신은 xml.dom.minidom 사용할 수 있습니다

from xml.dom import minidom 

def parse_customer_data(response_xml): 
    results = [] 
    dom = minidom.parseString(response_xml) 
    customers=dom.getElementsByTagName('Customer') 
    for c in customers:                              
     results.append({ 
      "cnum" : c.getElementsByTagName('CustomerNumber')[0].firstChild.data, 
      "lname" : c.getElementsByTagName('LastName')[0].firstChild.data, 
      "fname" : c.getElementsByTagName('FirstName')[0].firstChild.data 
     }) 
    return results 

if __name__ == "__main__": 
    response_xml = open("soap.xml").read() 
    results = parse_customer_data(response_xml) 
    print(results) 

메모를 그 입력 파일, soap.xml에 대한 : 1. I XML 버전/비누 추가 : 사용자가 제공 한 XML 약 봉투 요소, 그렇지 않으면 내가 내 코드를 테스트하기 위해 다른 고객 요소를 추가 2. 분석 할 것이다

출력 :

$ python soap.py 
[{'lname': u'NAME1', 'cnum': u'1051012', 'fname': u'BASIC1'}, {'lname': u'NAME2', 'cnum': u'1051013', 'fname': u'BASIC2'}] 
+0

제안 해 주셔서 감사합니다. 그것은 잘 작동했다. 나는 다른 플러그인을 설치할 필요가 없었기 때문에 다른 대답과 함께 갔다. – DarthOpto

관련 문제