request.put()但它请求使用PUT在我的Python上使用GET
即使我使用requests.put()
,服务器也将它的请求识别为“GET”。request.put()但它请求使用PUT在我的Python上使用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”。
哪个是错我的代码?
增加了更多。
我修正了下面的代码,发现302重定向是通过检查r.history发生的。 但仍然坚持为什么302发生。
当我比较邮差。它显示正确。
你几乎肯定被重定向。发送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 = {
"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
头作为一个额外的好处:
headers = {"x-api-key": "test_api_dp" }
r = requests.put(url, json=payload, headers=headers)
再次,这假定是一个Python数据结构,不在Python字符串JSON文件。
你说得对。我可以找出页面重定向。 r.history告诉302代码。 但我仍然不知道为什么302重定向。 与邮差相比。它响应正确。 我客人wireshark不显示https数据包。 – sungyong
@sungyong:不,wireshark无法显示加密数据。它可能会列出数据包,但无法解密有效负载以显示HTTP级别的信息。 –
@sungyong:我看不到你发送的是什么有效载荷。可能是重定向主体包含更多信息,可能检查'r.history [0] .content'。标题中可能还有线索。这里没有足够的信息能够诊断任何事情,真的。 –
您可以简单地测试什么方法与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
是的,OP是错误的,当你使用'requests.put()'的时候,总是发送一个PUT请求。问题在于他们在wireshark中查看错误的请求。 –
'requests.put()'肯定发送'PUT'方法。你确定服务器没有响应'302'或'303'重定向吗? –
您在截图中显示的GET请求**与您的请求**不符。 PUT进入'/ test/partners/digital-pie/users/assignee',GET用于'/ partners/digital-pie/users/assignee'。我还注意到,该服务器以404请求响应该GET请求。 –
注意:当使用'json = payload'而不是'data'时,不需要使用'json.dumps()'或设置Content-Type'头。 –