python 3使用requests.put获取401

时间:2017-02-15 16:37:37

标签: python python-requests basic-authentication

我正在尝试将文件放入启用WebDav的URL。 代码如下所示:

headers = {'Authorization':'Basic', 'username': 'doc_iconx', 'password': 'doc_iconx'}
    id = "SOMEID"
    pw = "SOMEPW"
    try:
        url = 'https://mywebsite.com/Dir/'
        files = {'upload_file': open(fileName, 'rb')}
        r = requests.put(url,auth=HTTPDigestAuth(id,pw), files=files, headers={'User-Agent': 'Mozilla'
    })

我回来了:

<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

我知道ID /密码很好,因为我可以使用curl

进行put

任何想法?

2 个答案:

答案 0 :(得分:0)

由于您的身份验证方案使用的是Basic,因此您只需使用HTTPBasicAuth代替HTTPDigestAuth

r = requests.put(url,auth=HTTPBasicAuth(id,pw), files=files, headers={'User-Agent': 'Mozilla'})

requests实际上甚至有一个快捷方式,没有指定模式:

r = requests.put(url,auth=(id,pw), files=files, headers={'User-Agent': 'Mozilla'})

答案 1 :(得分:0)

我有两个不同的问题。 Sal,纠正了我的Auth错误。第二个错误是一个愚蠢的用户错误。我需要将我想要上传的文件名附加到URL的末尾。构建它的方式是尝试创建一个名为Report的文件。但是,Report是一个现有目录,我打算在其中编写该文件。