简体   繁体   English

POST请求文件python-requests

[英]POST request file python-requests

This is the goal of post request I need in python: 这是我在python中需要发布请求的目标:

I got XML file, url and authentication-token. 我得到了XML文件,URL和身份验证令牌。 Depending on the xml file I get the xml response from the server back. 根据xml文件,我从服务器返回xml响应。

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

Post request status code is 200, but there is error in xml response like " <error>invalid XML for request</error> ". 发布请求状态代码为200,但是xml响应中有错误,例如“ <error>invalid XML for request</error> ”。 Supposedly that xml file is filled in wrong parameter in my post request. 可能是我的帖子请求中的xml文件填写了错误的参数。 But in another tool - Postman - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en ? 但是在另一个工具- 邮递员中-https : //chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbbddddopop ? hl= zh - CN吗? it works and succeeds with the correct xml response. 它可以正常工作,并以正确的xml响应成功。 What I have in Postman: 我在邮递员中拥有的东西:

  • in Headers: Key : Auth-token Value : abCdeFgh 在标题中: 密钥 :Auth-token :abCdeFgh

  • in Body: form-data option chosen.. Key : data Value : sample_plan.xml file chosen.. 在正文中:选择了表单数据选项。 :数据 :选择了sample_plan.xml文件。

Goal for parameters (all parameters are mandatory) of post request: 1. in header - Authentication-Token 2. in body - XML file with name/contentID = data 发布请求的参数目标(所有参数均为必需参数):1.在标题中-身份验证令牌2.在正文中-名称/内容ID =数据的XML文件

Which parameter should I put the file of the post request into? 我应该将发布请求的文件放入哪个参数? I've tried almost everything - based on python-requests documentation... 我已经尝试了几乎所有内容-根据python-requests文档...

Thanks for your help! 谢谢你的帮助!

Somehow after hours of trying I got it! 经过数小时的尝试,我终于明白了!

The right parameter was files and there had to be 'data' key with value of tuple with 3 arguments. 正确的参数是文件,并且必须有带有三个参数的元组值的“数据”键。 Otherwise it didn't function properly... 否则它将无法正常运行...

From the requests documentation I used files parameter for multipart encoding upload http://docs.python-requests.org/en/master/api/ with key 'data' which I was urged by + value of 3-tuple ('filename', fileobj, 'content_type') 从请求文档中,我使用files参数进行多部分编码上传http://docs.python-requests.org/en/master/api/键为 “数据”,我强烈要求3元组的+ 值(“文件名” ,fileobj,“ content_type”)

Therefore the answer for my problem is (also using 'with' keyword so the file is properly closed after its suite finishes) 因此,我的问题的答案是(也使用'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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM