我遇到了一个我似乎无法解决的非常奇怪的问题:
我已经在我的 wordpress 网站 上设置了 REST API 和一个 Oauth1 服务器。
我以前能够使用python 请求库 连接到服务器并上传新帖子,但是,2 个月后我重新访问了代码,现在它不起作用了。错误响应显示:b'{"code":"json_oauth1_signature_mismatch","message":"OAuth signature does not match","data":{"status":401}}'
我可以连接到 Oauth1 服务器并通过 Postman HTTP 请求生成器将新帖子上传到我的网站,所以看来网站不是问题所在。
代码也不是问题,因为自从它上次运行良好以来,我在过去 2 个月内没有更改它。此外,我还在本地托管的 wordpress 安装上对其进行了测试,它运行良好。
代码的精简版本如下所示:
import requests
from requests_oauthlib import OAuth1
OAuth_credentials = {
'client_key': 'X',
'client_secret': 'X',
'resource_owner_key': 'X',
'resource_owner_secret': 'X'
}
auth = OAuth1(*OAuth_credentials.values())
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
data = {
'title': 'title'
}
response = requests.request(
'POST',
'https://www.X.com/wp-json/WP/v2/posts/',
headers=headers,
auth=auth,
json = data
)
Postman 正在工作但 python 请求库不工作对我来说似乎很奇怪。我只能认为我一定是在我的网站上更改了一些东西,例如 htaccess,但我没有运气进行那条查询。
我的 .htaccess 看起来像这样:
# BEGIN HTTPS Redirection Plugin
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteBase /
RewriteRule ^index\.php$ - [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
</IfModule>
# END HTTPS Redirection Plugin
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
任何人都可以提出问题可能是什么吗?
最佳答案
我现在已经解决了这个问题。我发现出于某种原因,wordpress 不喜欢 http 请求中的请求用户代理。我更改它,现在它可以工作了。
关于python-3.x - Wordpress REST API、Oauth1 和 python 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964667/