[Python] How to upload an image with the wordpress api in Python?

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I hope your are fine.

    I would like to upload an image in my wordpress library from my computer. I wrote few lines in Python that use Wordpress API.

    It is working when I use 'Content-Type': 'application/x-www-form-urlencoded' However, the content added is not an image.

    When I change it with 'Content-Type': 'image/jpg' I get an error message which says: Error 403 please forward this error screen to the site owner

    What should I do, contact my web hosting company ?

    Thank you all for you help

    Here is my code:

    from requests_toolbelt.multipart.encoder import MultipartEncoder
    import requests
    import base64
    import json
    import time
    import os


    user = "user"
    password = "pass"

    url = "https://example.com/wp-json/wp/v2"
    data_string = user + ':' + password

    token = base64.b64encode(data_string.encode())

    # headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
    headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'application/x-www-form-urlencoded','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}



    video = {
    "title": "test",
    "description": "description",
    "media-type": "image",
    }

    r = requests.post(url + "/media", headers=headers, json=video)
    print(r.text)

    Continue reading...

Compartilhe esta Página