我正在尝试将数据库(SQLite)作为 JSON 文件发送并将其发布在 Wordpress 中(我还想编辑行和列等),但是当我这样做时,用 python 中的请求库做一个简单的帖子让我感到困惑当我使用这行代码时出现此错误:
header = {"user": username, "password": password}
response = requests.post(url, headers=header, json=data)
{"code":"rest_cannot_edit","message":"Lo siento, no tienes permisos para editar esta entrada。","data":{"status":401}}
但是,当我在 requests.post 函数中使用 auth 时,它可以工作,它仅使用以下命令发送信息:
response = requests.post(url, auth=(username, password), json=data)
我的回复状态也是 200(发布正确完成!)
根据我发现的所有论坛,我需要插件应用程序密码,是的,我已经创建了我的令牌密码并且就像上面一样工作,为什么?
所有代码:
import requests
#PAGE WHERE I WANT TO SEND INFO
url = "https://dca-mx.com/wp-json/wp/v2/pages/362"
username = 'Fabian'
# The application password you generated
password = 'XXXX XXXX XXXX XXXX XXXX'
# The post data
data = {
'title': 'DCA DB',
'content': 'HELLO FROM PYTHON.',
'status': 'publish'
}
header = {"user": username, "password": password}
# Send the HTTP request THIS WORKS
response = requests.post(url, auth=(username, password), json=data)
#THIS DOES NOT WORKS WHY??????!!!!!!!!!!!
response = requests.post(url, headers=header, json=data)
# Check the response
if response.status_code == 201:
print('Post created successfully')
elif response.status_code == 200:
print('Posteado Correctamente!')
else:
print(response.text)
问题在于您的
requests.post
调用中如何处理身份验证。使用 WordPress REST API 处理身份验证有两种主要方法。
当您使用 auth 参数时,您正在使用基本身份验证,这就是它起作用的原因,请检查您的代码:
response = requests.post(url, auth=(username, password), json=data)
.
虽然 auth 参数在内部为基本认证设置了正确的授权标头,但直接使用标头时,您需要正确格式化授权标头。您使用的标头字典的格式不适合基本身份验证。因此,您需要使用 Base64 编码的字符串
Authorization
设置 username:password
标头。
试试这个:
import requests
import base64
# PAGE WHERE I WANT TO SEND INFO
url = "https://dca-mx.com/wp-json/wp/v2/pages/362"
username = 'Fabian'
# The application password you generated
password = 'XXXX XXXX XXXX XXXX XXXX'
# The post data
data = {
'title': 'DCA DB',
'content': 'HELLO FROM PYTHON.',
'status': 'publish'
}
# Encode the username and password
credentials = f"{username}:{password}"
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
header = {"Authorization": f"Basic {encoded_credentials}"}
# Send the HTTP request (it should still work)
response = requests.post(url, headers=header, json=data)
# Now, check the response
if response.status_code == 201:
print('Post created successfully')
elif response.status_code == 200:
print('Posteado Correctamente!')
else:
print(response.text)
希望它有帮助,让我更新!