PUT Python请求未更新数据

时间:2018-09-05 09:09:13

标签: python-2.7 api python-requests put

编辑更新:

我尝试了此页面上给出的解决方案,但对我也不起作用: 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网址放在我要使用此请求的位置时,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)

如何在不使用上面邮递员示例中给出的边界值的情况下编写查询?这只是表单数据中的一个简单的PUT请求。值可以是一个或多个。在上面的示例中,我仅使用要通过PUT>

更改的“ lastName”

1 个答案:

答案 0 :(得分:1)

处理边界条件的最佳方法是multipartencoder。 https://toolbelt.readthedocs.io/en/latest/uploading-data.html

您可以尝试以下代码。

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

m = MultipartEncoder(
    fields={'field0': 'value', 'field1': 'value',
            'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
    )

r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})