python - 如何使用 requests 模块将 SOAP 体内的值作为参数传递

标签 python python-2.7 ipython python-requests

我编写了以下代码,该代码可以成功执行。但是,我想将 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)

最佳答案

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 等模板引擎并使用上下文变量。

这里正确的解决方案是切换到肥皂水而不是请求

https://bitbucket.org/jurko/suds

编辑:Zeep 也是一个很好的肥皂库,比肥皂水更快 http://docs.python-zeep.org/en/master/

关于python - 如何使用 requests 模块将 SOAP 体内的值作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597371/

相关文章:

python - 在linux中,wx.PopupWindow从wx.Dialog弹出时没有得到任何鼠标事件?

python - 每当 Tkinter 小部件值更改时如何运行代码?

python - 如何过滤字典值(在另一个字典中)

python - Scipy 标签并测量每个标签中的最大像素

python - Ipython没有可用的readline并且pip install readline错误

python - IPython 控制台找不到 "backports.shutil_get_terminal_size"并且不会加载

python - 从原始WAV音频中获取信号的正负分量

mysql - SQLAlchemy 与 Google Cloud SQL 连接到开发服务器

python - 如何使用 web.py 显示图像

python - 具有动态深度和仅叶子数据的树结构