请求.put()但它请求在python上使用GET-by-PUT

2024-09-27 07:32:13 发布

您现在位置: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检查pack时,我可以知道我请求的代码是“GET”。在

wireshark packet

我的代码哪一个错了?在

增加了更多。在

我更正了下面的代码,通过检查r.history,我发现发生了302个重定向。 但仍然无法解释302发生的原因。
当我和邮递员比较时。它显示正确。在

Comparison with postman

第二次添加。 requests variable watch window


Tags: 代码testimportapijsonurlgetput
2条回答

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

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

您可能会被重定向,因为您的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头作为附加奖励:

^{pr2}$

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

您可以简单地测试使用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'

如你所见,所用的方法是

相关问题 更多 >

    热门问题