【问题标题】:POST request file python-requestsPOST 请求文件 python-requests
【发布时间】:2018-02-09 08:20:27
【问题描述】:

这是我在 python 中需要的 post 请求的目标:

我得到了 XML 文件、url 和身份验证令牌。根据 xml 文件,我会从服务器返回 xml 响应。

req = requests.post(url='http://abc123.com/index.php/plan/', \     
            headers={'auth-token': 'abCdeFgh'}, \
            data={'data': open('sample_plan.xml', 'rb')})

发布请求状态码为 200,但 xml 响应中有错误,如“<error>invalid XML for request</error>”。假设该xml文件在我的发布请求中填写了错误的参数。 但在另一个工具中 - Postman - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en?它以正确的 xml 响应工作并成功。我在 Postman 中拥有的东西:

  • 在标题中: Key:Auth-token Value:abCdeFgh

  • 在正文中: 选择了表单数据选项.. Key:数据 Value:选择的 sample_plan.xml 文件..

post请求的参数目标(所有参数都是强制性的): 1. 在标头中 - Authentication-Token 2. 在正文中 - 名称/contentID = 数据的 XML 文件

我应该将post请求的文件放入哪个参数?我几乎尝试了所有方法 - 基于 python-requests 文档...

感谢您的帮助!

【问题讨论】:

    标签: python post request python-requests postman


    【解决方案1】:

    经过几个小时的尝试,我终于搞定了!

    正确的参数是文件,并且必须有带有 3 个参数的元组值的“数据”键。否则它不能正常工作......

    从请求文档中,我使用 files 参数进行分段编码上传http://docs.python-requests.org/en/master/api/ 使用 key 'data' 我被 + value of 3-tuple ('filename', fileobj, 'content_type') 所催促

    因此我的问题的答案是(也使用'with'关键字,因此文件在套件完成后正确关闭)

    with open('sample_plan.xml', 'rb') as payload:
        headers = {'auth-token': 'abCdeFgh'}
        files = {'data': ('sample_plan.xml', payload, 'text/xml')}
        req = requests.post(url='http://abc123.com/index.php/plan/', \
                headers=headers, files=files)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 2015-06-11
      • 2015-05-18
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2015-04-23
      相关资源
      最近更新 更多