Publish WordPress Post with Python Requests and RE

2019-04-15 22:55发布

问题:

I try to publish post to WordPress blog with python requests and rest api by following code:

auth = 'Basic ' + str(base64.b64encode(b'admin:123456'), 'utf-8')
headers = {'Authorization': auth}
body = {'title': 'Hello World'}
r = requests.post('wp-json/wp/v2/posts', headers=headers, data=body)

and always got 401 error:

>>> r.text
'{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}'

I'm pretty sure that the account admin and password is correct and has administrator role, Did I miss anything?

回答1:

I was able to solve this

A. I installed & activated this plugin on my wordpress https://wordpress.org/plugins/application-passwords/

B. follow the help text there and create your password string for your userid - assume it is mypassword123

C. now do this on your terminal "admin:mypassword123" | base64

You will get a new password - say pwdabc123

D. Code looks like

url_srcdest = "http://example.com/wp-json/wp/v2/pages/"
headers = {'Content-Type': 'application/json', 
         'Authorization': 'Basic pwdabc123',
         'Username': '<your username>', 
         'Password':'pwdabc123'}
data = \
    {
        "title":"Testing via API via Python",
        "content":"tEST CONTENT OF THE THIS TEST PAGE via PYTHON",
        "status": "publish"
    }

response = requests.post(url_srcdest, data=json.dumps(data), headers=headers)