rest api - Wordpress Error uploading image: 401 API Python Script

admin2025-01-07  7

I have this script in python to try to upload an image. But First I added one ‘Application Password’ in my profile of wordpress. I have the key and all the user name is ‘admin’

However, the script gives me this error:

‘Error uploading image: 401 - {"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}
Image upload failed.’

What could be wrong or I miss to configure?

This is the script:

import requests
from requests.auth import HTTPBasicAuth
import os
import base64

# WordPress API credentials
WP_USER = 'admin'  # Your WordPress username
WP_APPLICATION_PASSWORD = 'xxx'  # Your WordPress application password
WP_URL = ";  # Your WordPress site URL

def upload_image_to_wp(imgPath):
    """
    Upload an image to WordPress via the REST API using application password authentication.
    
    :param imgPath: Local path to the image to upload.
    :return: The image ID and URL if successful, else None.
    """
    url = f'{WP_URL}/wp-json/wp/v2/media'

    # Create the Authorization header manually
    auth = HTTPBasicAuth(WP_USER, WP_APPLICATION_PASSWORD)
    auth_header = {
        'Authorization': 'Basic ' + WP_USER + ':' + WP_APPLICATION_PASSWORD,
        'Content-Type': 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        'Content-Disposition': f'attachment; filename={os.path.basename(imgPath)}',
        'Cache-Control': 'no-cache',
    }

    with open(imgPath, 'rb') as file:
        file_data = {
            'file': (os.path.basename(imgPath), file, 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png')
        }

        # Adding Content-Disposition header
        headers = {
            'Content-Disposition': 'attachment; filename="image.jpg"'  # Adjust filename as needed
        }

        try:
            response = requests.post(url, files=file_data, headers={**auth_header, **headers})

            if response.status_code == 201:
                new_dict = response.json()
                image_id = new_dict.get('id')
                image_url = new_dict.get('guid', {}).get('rendered')
                return image_id, image_url
            else:
                print(f"Error uploading image: {response.status_code} - {response.text}")
                return None
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")
            return None

# Example usage
image_path = r"C:/jpg.jpg"  # Replace with the actual path to the image
upload_response = upload_image_to_wp(image_path)

if upload_response:
    image_id, image_url = upload_response
    print(f"Image uploaded successfully! ID: {image_id}, URL: {image_url}")
else:
    print("Image upload failed.")

I have this script in python to try to upload an image. But First I added one ‘Application Password’ in my profile of wordpress. I have the key and all the user name is ‘admin’

However, the script gives me this error:

‘Error uploading image: 401 - {"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}
Image upload failed.’

What could be wrong or I miss to configure?

This is the script:

import requests
from requests.auth import HTTPBasicAuth
import os
import base64

# WordPress API credentials
WP_USER = 'admin'  # Your WordPress username
WP_APPLICATION_PASSWORD = 'xxx'  # Your WordPress application password
WP_URL = "https://xxx.xxx.com"  # Your WordPress site URL

def upload_image_to_wp(imgPath):
    """
    Upload an image to WordPress via the REST API using application password authentication.
    
    :param imgPath: Local path to the image to upload.
    :return: The image ID and URL if successful, else None.
    """
    url = f'{WP_URL}/wp-json/wp/v2/media'

    # Create the Authorization header manually
    auth = HTTPBasicAuth(WP_USER, WP_APPLICATION_PASSWORD)
    auth_header = {
        'Authorization': 'Basic ' + WP_USER + ':' + WP_APPLICATION_PASSWORD,
        'Content-Type': 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        'Content-Disposition': f'attachment; filename={os.path.basename(imgPath)}',
        'Cache-Control': 'no-cache',
    }

    with open(imgPath, 'rb') as file:
        file_data = {
            'file': (os.path.basename(imgPath), file, 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png')
        }

        # Adding Content-Disposition header
        headers = {
            'Content-Disposition': 'attachment; filename="image.jpg"'  # Adjust filename as needed
        }

        try:
            response = requests.post(url, files=file_data, headers={**auth_header, **headers})

            if response.status_code == 201:
                new_dict = response.json()
                image_id = new_dict.get('id')
                image_url = new_dict.get('guid', {}).get('rendered')
                return image_id, image_url
            else:
                print(f"Error uploading image: {response.status_code} - {response.text}")
                return None
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")
            return None

# Example usage
image_path = r"C:/jpg.jpg"  # Replace with the actual path to the image
upload_response = upload_image_to_wp(image_path)

if upload_response:
    image_id, image_url = upload_response
    print(f"Image uploaded successfully! ID: {image_id}, URL: {image_url}")
else:
    print("Image upload failed.")
Share Improve this question asked Jan 2 at 1:18 coerracecoerrace 101 New contributor coerrace is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

1 Answer 1

Reset to default 0

When you're using Basic Authentication, you can't just pass the {username}:{password} string; you need to base64-encode it.

libcurl docs on Basic Auth

So your line

'Authorization': 'Basic ' + WP_USER + ':' + WP_APPLICATION_PASSWORD

should be more like

'Authorization': 'Basic ' + base64( WP_USER + ':' + WP_APPLICATION_PASSWORD )

(I don't know how Python does base64, but it looks like you're already importing a related library in your Python snippet.)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736253890a160.html

最新回复(0)