我正在嘗試向需要 http 身份驗證的服務器發送 API 請求。
(Wordpress 服務器)設定為使用基本身份驗證對 API 進行身份驗證。
首先,我使用代碼設定會話
with requests.sessions.Session() as session:
session.auth = ('my_user', 'my_password')
session.get(url)
我按預期得到200。
然后我發送 API 請求
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " token.decode('utf-8')}
response = requests.get(url=url, headers=header)
但我在回應中收到錯誤 401。
我怎樣才能以不同的方式讓它發揮作用?
uj5u.com熱心網友回復:
我有一些我的樣本,希望對你有幫助:
header = {....}
data = {...}
response= requests.post(url=url, data=data,headers=header,auth=(user,password))
uj5u.com熱心網友回復:
據我所知,wordpress 默認情況下甚至不接受身份驗證用戶/密碼。
您只能通過 cookie 登錄(來源)
但是有一種方法可以使用用戶/密碼來驗證 rest api,那就是插件。我建議Wordpress REST API 身份驗證
那么使用將如此簡單,例如:
import requests
headers = {
'Authorization': 'Basic base64encoded <username:password>',
'Content-Type': 'application/x-www-form-urlencoded',
}
data = 'title=sample post&status=publish'
response = requests.post('http://example.com/wp-json/wp/v2/posts', headers=headers, data=data)
uj5u.com熱心網友回復:
從這兩個答案中(謝謝!),這里是兩者合并的答案。
API 身份驗證在標頭中發送(WP 中需要 API 身份驗證插件)。
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " token.decode('utf-8')}
會話認證在請求的 auth 引數中發送
response = requests.get(url=url, headers=header, auth=('my_user', 'my_password'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/479384.html
上一篇:如何從資產檔案夾中獲取影像?
