我编写了以下成功执行的代码。但是,我希望将username
作为参数传递,而不是直接在其中进行硬编码
肥皂体。
import requests
url = "url?WSDL"
headers = {"Content-Type": "text/xml;charset=UTF-8"}
body = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header>
<tem:Authentication>
<!--Optional:-->
<tem:UserName>username</tem:UserName>
<!--Optional:-->
<tem:Password>password</tem:Password>
</tem:Authentication>
</soapenv:Header>
<soapenv:Body>
<tem:func1>
<!--Optional:-->
<tem:incident_number>INC000005215731</tem:incident_number>
<!--Optional:-->
<tem:wii>
<tem:Submitted>false</tem:Submitted>
<tem:Work_Info_Type>General_Information</tem:Work_Info_Type>
<!--Optional:-->
<tem:Summary>test</tem:Summary>
</tem:wii>
</tem:func1>
</soapenv:Body>
</soapenv:Envelope>"""
response = requests.post(url, data=body, headers=headers)
print response.content
另外,如何使用suds
转换上述代码?
到目前为止,我编写了以下代码:
from suds.client import Client
import logging
client = Client("url?WSDL")
user = client.factory.create('Authentication')
user['UserName'] = 'username'
user['Password'] = 'password'
client.set_options(soapheaders=user)
答案 0 :(得分:1)
body = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header>
<tem:Authentication>
<!--Optional:-->
<tem:UserName>{username}</tem:UserName>
<!--Optional:-->
<tem:Password>{password}</tem:Password>
</tem:Authentication>
</soapenv:Header>"""
response = requests.post(url, data=body.format(username="bob", password="abc123"), headers=headers)
你也可以使用像django / jinja2这样的模板引擎并使用上下文变量。
这里适当的解决方案是切换到suds而不是请求
https://bitbucket.org/jurko/suds
编辑:Zeep也是一个比肥皂泡更快的肥皂库 http://docs.python-zeep.org/en/master/