request.put() 但它要求在我的 python 上使用 PUT 的 GET

request.put() but it request using GET by PUT on my python

即使我使用 requests.put(),服务器也将其请求识别为 "GET"。

这是我的代码。

import requests
import json

url = 'https://api.domain.com/test/partners/digital-pie/users/assignee'
payload = """
{
"assignee": {
"district": "3",
"phone": "01010001000",
"carNum": "598865"
},
"deduction": {
"min": 1000,
"max": 2000
},
"meta": {
"unit-label": "1-1-1",
"year": "2017",
"quarter": "2"
}
}
"""

headers = {"content-type": "application/json", "x-api-key": "test_api_dp" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

print("status code:", r.status_code)
print('encoding:', r.encoding)
print('text:', r.text)
print('json:', r.json())

当我通过 wireshark 检查包时,我可以知道我请求的代码是 "GET"。

我的代码哪里有问题?

添加了更多。

我修改了如下代码,检查r.history发现302重定向发生了。 但是还是卡住了为什么会出现302。
当我比作邮递员时。它显示正确。

Comparison with postman

加法第二。 requests variable watch window

您可以通过 http://httpbin.org

简单地测试使用的是什么方法
>>> import requests
>>> r = requests.put('http://httpbin.org/anything')
>>> r.content
b'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {}, \n  
"headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", 
\n    "Connection": "close", \n    "Content-Length": "0", \n    "Host": 
"httpbin.org", \n    "User-Agent": "python-requests/2.18.3"\n  }, \n  
"json": null, \n  "method": "PUT", \n  "origin": "91.232.13.2", \n  "url": 
"http://httpbin.org/anything"\n}\n'

如您所见,使用的方法是 PUT

您几乎可以肯定被重定向。 PUT 请求 已发送 ,但服务器响应 3xx redirection response code,随后 requests 发出 GET 请求。我注意到您的 wireshark 屏幕截图中的路径与代码中使用的路径不匹配(缺少 /test 前缀),进一步添加了重定向已发生的证据。

您可以通过查看 r.history(每个条目都是另一个响应 object)来检查 redirection history,或者将 allow_redirects=False 设置为不响应重定向(您得到第一反应,没有别的)。

您可能会被重定向,因为您是 double-encoding 您的 JSON 负载。没有必要在 已经是 JSON 文档 的字符串上使用 json.dumps。您正在发送一个 JSON 字符串,其内容恰好是一个 JSON 文档。这几乎肯定是发送错误的东西。

通过删除 json.dumps() 调用或将 payload 字符串 替换为 字典 来更正此问题:

payload = {
    "assignee": {
        "district": "3",
        "phone": "01010001000",
        "carNum": "598865"
    },
    "deduction": {
        "min": 1000,
        "max": 2000
    },
    "meta": {
        "unit-label": "1-1-1",
        "year": "2017",
        "quarter": "2"
    }
}

顺便说一句,你最好使用 json 关键字参数;您将获得 Content-Type: application/json header 作为额外奖励:

headers = {"x-api-key": "test_api_dp" }    
r = requests.put(url, json=payload, headers=headers)

同样,这假设 payload 是一个 Python 数据结构, 而不是 JSON 文档在 Python字符串。