PUT Python请求不会更新数据

问题描述 投票:0回答:1

编辑更新:

我尝试了这个页面上给出的解决方案,但这对我来说也不起作用: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请求。值可以是一个或多个。在上面的例子中,我只使用'lastName',我想通过PUT>更改

python-2.7 api python-requests put
1个回答
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})
© www.soinside.com 2019 - 2024. All rights reserved.