通过REST API上传图片或者其余媒体文件。
#这是第一种方式
import requests
import base64
# Credentials and endpoint
username = "website_user_name_loginName" #real user name, not the application name. 注意这里的用户名是登陆的用户名。
password = "user_profile_application_password$" #Dashboard->User->Profile->Application Passwords,注意这里的密码是应用密码,不是登陆密码
api_url = 'https://your_website_domain_name.xxxxxxx/wp-json/wp/v2/media'
# File path
file_path = 'test.webp'
# Open the file and read its binary data
with open(file_path, 'rb') as file:
file_data = file.read()
# Headers for the request
headers = {
'Authorization': 'Basic ' + base64.b64encode(f'{username}:{password}'.encode()).decode(),
'Accept': 'application/json', # The API returns JSON
'Content-Type': 'application/binary', # Set content type to binary
'Content-Disposition': f'attachment; filename={file_path.split("/")[-1]}' # Set file name
}
# Make the POST request
response = requests.post(api_url, headers=headers, data=file_data)
# Check the response
if response.status_code == 201: # 201 Created
print("Upload successful!")
print("Response:", response.json())
else:
print(f"Failed to upload. Status code: {response.status_code}")
print("Response:", response.text)
# Assuming 'response' is the Response object from requests
try:
# Parse JSON from the response
response_data = response.json()
# Extract the uploaded image URL
uploaded_image_url = response_data.get("source_url", None)
# Print the URL
if uploaded_image_url:
print(f"Uploaded Image URL: {uploaded_image_url}")
else:
print("Image URL not found in the response.")
except Exception as e:
print(f"An error occurred: {e}")
第二种方式,可以设置图片的Title、ALT等
#第二种方式,这个方式可以设置图片的Alt
import requests
import base64
# Credentials and endpoint
username = "login_user_name" #real user name, not the application name
password = "application_password" #Dashboard->User->Profile->Application Passwords
#upload media endpoint
host = 'https://your_domain_name.xxxxx/wp-json/wp/v2/media'
# Authentication using Basic Auth
auth = (username, password)
# File path
file_path = 'test.webp'
# Metadata for the upload
data = {
"status": "draft",
"title": "Photo media",
"description": "Photo media",
"media_type": "image",
"alt_text": "alternate text"
}
try:
# Read the image file in binary mode
with open(file_path, 'rb') as img_file:
file_data = img_file.read()
# Prepare headers
headers = {
'Content-Type': 'image/webp',
'Content-Disposition': f'attachment; filename="{file_path.split("/")[-1]}"',
}
# Make the POST request
response = requests.post(
host,
auth=auth,
headers=headers,
data=file_data,
params=data # Additional metadata as query params
)
# Handle response
if response.status_code == 201:
print("Upload successful!")
print("Response:", response.json())
else:
print(f"Failed to upload. Status code: {response.status_code}")
print("Response:", response.text)
except Exception as e:
print(f"An error occurred: {e}")
# Assuming 'response' is the Response object from requests
try:
# Parse JSON from the response
response_data = response.json()
# Extract the uploaded image URL
uploaded_image_url = response_data.get("source_url", None)
# Print the URL
if uploaded_image_url:
print(f"Uploaded Image URL: {uploaded_image_url}")
else:
print("Image URL not found in the response.")
except Exception as e:
print(f"An error occurred: {e}")
WordPress上传图片以后,会自动生成不同尺寸的图片,比如上传的是dog.jpg, 可能会生成dog-600*600.jpg, dog-300*300.jpg, 本来一张图片只有100KB,但是自动生成了好几张,存储空间可能就翻倍了。如果不需要自动生成,可以使用如下代码,放到theme->function.php文件中
function disable_image_sizes_for_rest_api($sizes) {
// 检查是否通过 REST API 上传图片
if (defined('REST_REQUEST') && REST_REQUEST) {
return []; // 禁止生成任何额外尺寸
}
return $sizes; // 非 REST API 上传仍正常处理
}
add_filter('intermediate_image_sizes_advanced', 'disable_image_sizes_for_rest_api');
Leave a Reply