无法使用Wordpress API上传媒体文件(通过python)

时间:2018-12-02 12:06:31

标签: python wordpress session-cookies wordpress-rest-api nonce

我正在尝试通过python将文件上传到wordpress媒体库,但是出现以下错误。

I am getting below error { 'code': 'rest_cannot_create', 'data': {'status': 401}, 'message': 'Sorry, you are not allowed to create posts as this user.'}

我已经在wordpress中安装了基本身份验证并启用了它。这是我的代码:

import sys
import os
import ntpath
import getpass
import requests
import pprint

url='http://rparthiban.com/articles/wp-json/wp/v2/media'


import csv
result_paths = []

user = input('Username:')
password = getpass.getpass('Password:')


session = requests.Session()
with open('list_html.csv') as csvfile:
    ipynb_reader = csv.reader(csvfile)
    for each_row in ipynb_reader:
        current_file =  each_row[0]
        # print(current_file)

        data = open(current_file, 'rb').read()
        fileName = os.path.basename(current_file)

        res = requests.post(url,
                            data=data,
                            headers={ 'User-Agent': 'Mozilla/5.0', 'Content-Type': '','Content-Disposition' : 'attachment; filename=%s'% fileName},
                            auth=(user, password))
        pp = pprint.PrettyPrinter(indent=4) ## print it pretty. 
        pp.pprint(res.json()) #this is nice when you need it
        # newDict=res.json()
        # newID= newDict.get('id')
        # link = newDict.get('guid').get("rendered")
        # print(newID, link)

链接here讨论了要提供的随机数,但是我不知道如何在此处生成和提供(webdev中的一个菜鸟)。请帮助。

1 个答案:

答案 0 :(得分:0)

401响应的意思是:未经授权。

这意味着您发送的凭据可能错误。

您还可以先登录,然后通过API调用发送承载令牌。

def esta (elemento,lista):                      ##here create a function with element 
    for i in range (len(lista)):                ## in a list, and search the [i]
        if lista[i]==elemento:
            return i
    return -1

## principal program:

abc=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a","b"]
a="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
cad=""
cont=0
for car in a:
    if esta(car,abc)!=-1:
        cad=cad+abc[esta(car,abc)+2]
    else:
        cad=cad+car
print(cad)