编程 POST 到使用基本身份验证的 django 网站?

Programmatic POST to django website that uses basic authentication?

我有一个 Django restful API(使用 django-rest-framework),其中 POST 请求需要事先验证。我想通过将数据发送到 API 来填充数据库,但是,我不知道如何以编程方式进行身份验证。到目前为止,我尝试了 requestspycurlhttplib2

import httplib2
from urllib.parse import urlencode

h = httplib2.Http(".cache")

h.add_credentials(username, password)

headers = {'Content-type': 'application/x-www-form-urlencoded'}

data = {
    "label": "SA2",
    "flagged": "false",
    "notes": ""
}

resp, content = h.request(
    "https://example.com/api/data", "POST", urlencode(data), headers=headers
)

resp
>>>
{
 'server': 'nginx/1.18.0 (Ubuntu)', 
 'date': 'Sat, 05 Mar 2022 00:06:32 GMT', 
 'content-type': 'text/html', 
 'transfer-encoding': 'chunked', 
 'connection': 'keep-alive', 
 'cross-origin-opener-policy': 'same-origin', 
 'referrer-policy': 'same-origin', 
 'vary': 'Origin', 
 'x-content-type-options': 'nosniff', 
 'x-frame-options': 'DENY', 
 'status': '403', 
 'content-length': '1867', 
 '-content-encoding': 'gzip'
}

content
>>>
b'{"detail":"Authentication credentials were not provided."}'

在浏览器中,我首先要访问登录页面。然后该网站发送一个 CRFT 令牌。 Here 是使用 curlbash 的解决方案。我更喜欢使用 Python.

您需要在 header 中提供凭据。

import base64

# ...
username="<username>"
password="<password>"
credentials=username + ":" + password

encoded_credentials = base64.b64encode(credentials.encode()).decode()
headers["Authorization"] = "Basic " + encoded_credentials

# ...

https://www.ibm.com/docs/en/ibm-mq/9.0?topic=security-using-http-basic-authentication-rest-api