python-requests:POST有效,PUT失败-“未提供身份验证凭据。”

时间:2019-04-22 13:57:34

标签: django django-rest-framework python-requests authorization

使用更多更新再次编辑:

尝试对python请求进行故障排除,以查看PUT请求是否有问题,但不确定如何继续。

下面是我的代码段:

def API_request(url=None, headers=None, payload=None, update=False):
    r = None
    if update and headers and payload:
        print "put request to %s with %s of %s" % (url, headers, payload)
        r = requests.put(url, headers=headers, data=payload)
    if headers and payload and not update:
        print "post request to %s with %s of %s" % (url, headers, payload)
        r = requests.post(url, headers=headers, data=payload)

    print r.status_code
    print r.text

当上面的命令发送POST请求创建记录时,它就起作用了。但是,每当它发送PUT请求时,都会出现401错误:“未提供身份验证凭据”。这会在多个端点上发生。

401
{"detail":"Authentication credentials were not provided."}

如果我将上述PUT打印功能的相关打印输出复制/粘贴到直接的HTTPie请求中,则它将起作用。以下请求将在服务器上成功返回200并更新记录:

http --debug PUT [url] < [file containing payload]  Authorization:'Token [token]'

如果我硬编码一个简单的脚本,除了将python和json导入并使用相同的标头(从原始语句打印)将完全相同的数据输入到相同的url,它就可以工作。下面的脚本会在服务器上成功返回200并更新记录:

import requests, json

url = "[my url"
headers = {'Content-Type': 'application/json', 'Authorization': 'Token [my token]'}
data = {[my data]}
payload = json.dumps(data)

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

print r.status_code
print r.text

我已将两个脚本中的信息发送到https://requestbin.fullcontact.com/,它们看起来是相同的。

大问题:

经过一整天的调试,我发现即使生成401错误的请求也成功命中了服务器并更新了相应的记录。简而言之,如果没有正确的功能验证,这将是不可能的。鉴于此,为什么我会从PUT请求中收到401错误?

很高兴回答评论中的任何问题。

1 个答案:

答案 0 :(得分:0)

The above was sending a follow-up GET request (without the header, so it was failing) after successfully sending the PUT request (which was succeeding). I caught this by logging all requests hitting the server.

I figured out why the follow up GET was being sent and corrected that. I still don't understand why the r.code and r.text response from the successful PUT was never printing and hitting the console. Had I seen that, it would have been much easier to find. However, since the main problem is resolved, I can't spend time troubleshooting that.

I should have been seeing both responses - the success and the fail in the console - problem for another time.