【问题标题】:How to pass values within soap body as parameter using requests module如何使用请求模块将肥皂体内的值作为参数传递
【发布时间】:2017-09-21 16:23:20
【问题描述】:

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

【问题讨论】:

    标签: python python-2.7 ipython python-requests


    【解决方案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 而不是 requests

    https://bitbucket.org/jurko/suds

    edit:Zeep 也是一个比 suds 更快的好肥皂库 http://docs.python-zeep.org/en/master/

    【讨论】:

    • 我已经尝试过suds,但我遇到了调试问题,这就是为什么我回到requests,我在原始问题中使用suds 添加了部分代码。你能建议如何走得更远吗?
    • 您遇到了什么问题?一些关于你的泡沫问题的细节会很有帮助。它是公共 WSDL 吗?您的设置似乎与我所做的相似,只是我认为 soapheaders 对我来说是一个列表
    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 2022-08-17
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多