在Python 3上使用API​​访问自动任务

时间:2015-05-08 00:41:16

标签: asp.net-web-api python-3.4

import urllib, requests, http.client
user = ""
pw = ""
apiurl = "https://webservices6.autotask.net/atservices/1.5/atws.wsdl"
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "https://webservices6.autotask.net/"
password_mgr.add_password(None, top_level_url, user, pw)
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(handler)
opener.open(apiurl)
urllib.request.install_opener(opener)
page = urllib.request.urlopen(apiurl)
SM_TEMPLATE ="""<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="https://webservices6.autotask.net/atservices/1.5/atws.wsdl" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
    <queryxml>
        <entity>Contact</entity>
        <query>
            <condition>
                <field>phone<expression op='equals'>#{phone}</expression></field>
            </condition>
        </query>
    </queryxml>
</env:Body>
</env:Envelope>"""

SoapMessage = SM_TEMPLATE%()
# construct and send the header  
webservice = http.client.HTTPSConnection("webservices6.autotask.net", 443)
webservice.putrequest("POST", "/atservices/1.5/atws.wsdl")
webservice.putheader("Host", "webservices6.autotask.net")
webservice.putheader("User-Agent", "Python post")
webservice.putheader("Content-type", "application/soap+xml; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(SoapMessage))
webservice.putheader("SOAPAction", "http://autotask.net/ATWS/v1_5/query")
webservice.endheaders()
webservice.send(SoapMessage.encode('utf-8'))
# get the response
statusmessage = webservice.getresponse()
print ("Response: ", statusmessage.read())

我写这个是为了查询,使用提供的API修改Autotask上的实体。但是,当我运行代码时,我发现了这个错误:

<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>

1 个答案:

答案 0 :(得分:0)

我有SUDS库在我的项目中集成AutoTask SOAP API。

我认为你错过了肥皂信封中的标题标签。使用SUDS库形成的信封,因为我直接调用API函数。请尝试更正您的信封,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://autotask.net/ATWS/v1_5/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <ns1:Body>
      <ns0:query>
         <ns0:sXML>
        <queryxml version="1.0">
            <entity>Contact</entity>
            <query>
                <field>phone<expression op="equals">#{phone}</expression></field>
            </query>
        </queryxml></ns0:sXML>
      </ns0:query>
   </ns1:Body>
</SOAP-ENV:Envelope>

请尝试将内容类型更改为

'Content-Type': 'text/xml; charset=utf-8'

如果您需要SUDS样品,请随时与我联系。