【发布时间】:2019-02-10 08:57:13
【问题描述】:
编辑更新:
我尝试了此页面上给出的解决方案,但这对我也不起作用: Put request working in curl, but not in Python
我正在使用 python 2.7。我正在尝试使用 PUT 请求。数据必须作为 formdata 发送。
import requests
import json
url = "http://httpbin.org/put"
data = {'lastName':'testNew'}
headers = {
'Authorization': "JWTeyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTc0LCJlbWFpbCI6ImNlbGVzdGlhbHRlc3QxQGdtYWlsLmNvbSIsInJhbmRvbV9qd3QiOiJlNXg1Q0oifQ.xc5jVAS6ZtTPrjg0LizznT0-sE9W_FkSW5s",
}
response = requests.request("PUT", url,data=data, headers=headers)
print(response.text)
这个请求给了我以下响应:
{
"args": {},
"data": "",
"files": {},
"form": {
"lastName": "testNew"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTc0LCJlbWFpbCI6ImNlbGVzdGlhbHRlc3QxQGdtYWlsLmNvbSIsInJhbmRvbV9qd3QiOiJlNXg1Q0oifQ.xc5jVAS6ZtTPrjg0LizznT0-sE9W_",
"Connection": "close",
"Content-Length": "16",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "111.93.35.2",
"url": "http://httpbin.org/put"
}
但是当我将 api url 放在我想使用这个请求的地方时,api 挂起并给出错误的连接错误。
我尝试更新值的 API 与 Postman 一起工作得很好,他们在剪贴板中提供的代码如下,它的工作方式就像一个更新数据的魅力:
import requests
url = "http://myUrl/dashboard/editProfile"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"lastName\"\r\n\r\nChangeLastFromCode\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Authorization': "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTc0LCJlbWFpbCI6ImNlbGVzdGlhbHRlc3QxQGdtYWlsLmNvbSIsInJhbmRvbV9qd3QiOiJlNXg1Q0oifQ.xc5jVAS6ZtTPrjg0LizznT0-sE9W_",
}
response = requests.request("PUT", url, data=payload, headers=headers)
print(response.text)
如何编写查询而不必使用上面 Postman 示例中给出的边界值?这只是表单数据中的一个简单的 PUT 请求。值可以是一个或多个。在上面的示例中,我只使用我想通过 PUT 更改的“lastName”>
【问题讨论】:
标签: python-2.7 api python-requests put