尝试通过 Hostgator 网站上安装的 WordPress 博客上的 Rest API 发布博客文章。它被 Mod_Security 阻止了

问题描述 投票:0回答:1

这是我正在使用的Python脚本:

import requests
from requests.auth import HTTPBasicAuth

url = 'https://my-phenomenal-website.com/blog/wp-json/wp/v2/posts'
data = {
    'title': 'TEST POST 1.1',
    'content': 'My outstanding content would go RIGHT HERE',
    'status': 'publish'
}

# Replace 'your_username' with the WordPress username
# Replace 'your_application_password' with the application password you created
auth = HTTPBasicAuth('USERNAME IS HERE', 'PASSWORD GOES HERE')

response = requests.post(url, json=data, auth=auth)

if response.status_code == 201:
    print("Post published successfully.")
else:
    print("Failed to publish post:", response.content)

使用我为每个用户创建的应用程序密码尝试了管理员用户名和另一个用户名。没有运气。回复如下:

Failed to publish post: b'<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>'

尝试修改根域和 /blog 子域上的 .htaccess 文件,以禁用 mod 安全性,正如许多人建议修复此问题一样。没有运气。仍然遇到同样的错误。

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

关于如何解决此问题的其他想法?

wordpress rest .htaccess hosting web-hosting
1个回答
0
投票

我花了几个小时试图解决这个问题,这对我有用:

import requests
import json  # Import for json.dumps

ROOT = 'https://your-website.com/blog/'
AUTH_USER = 'Your Wordpress Username'
AUTH_PASSWORD = 'Your password, created using the Application Passwords section under the above user in the Wordpress Users section'

headers = {
    'Content-Type': 'application/json',
    'User-Agent': 'My Python WordPress API Script'  # Anything will work here apparently, just important that BOTH of these are included.
}

data = {
    'title': 'Test WP API',
    'status': 'publish',
    'slug': 'test-wp-api',
    'author': 1,
    'content': 'This is my first post created using REST-API' # include ALL of these parameters for it to work properly
}

# Convert data to JSON format
data_json = json.dumps(data)

response = requests.post(url=ROOT + 'wp-json/wp/v2/posts', data=data_json, headers=headers, auth=(AUTH_USER, AUTH_PASSWORD))

if response.status_code == 201:
    print("Post published successfully.")
else:
    print("Failed to publish post:", response.content)
© www.soinside.com 2019 - 2024. All rights reserved.