网站更新内容:请访问: https://bigdata.ministep.cn/

wordpress使用python上传图片到缩略图

python 的上传图片到wordpress代码

import re
import requests
import json,os,pprint
import time
from numpy import *

site="https://bigdata.ministep.cn"

def get_token():
    session = requests.Session()
    url = '{site}/wp-json/jwt-auth/v1/token'.format(site=site)
    data = {
        'username':"bigdata.ministep.cn",
        'password':"bigdata.ministep.cn"
        }
    headers = {'user-agent': 'Mozolla/5.0',
               }
    resp = session.post(url, data=data, headers=headers, timeout=3335)  # 请求
    r = json.loads(resp.content)
    return r



def upload_images(imgPath):
    url = '{site}/wp-json/wp/v2/media'.format(site=site)
    data = open(imgPath, 'rb').read()
    fileName = os.path.basename(imgPath)
    res = session.post(url=url,
                        data=data,
                        headers={'user-agent': 'Mozolla/5.0','Authorization': 'Bearer ' + token, 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName},
                        )
    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)
    return (newID, link)


if  __name__=='__main__':
    r = get_token()
    token = r["data"]['token']
    session = requests.Session()
    # print (resp.text)
    #print(resp.json())
    # url = '{site}/wp-json/wp/v2/posts'.format(site=site)
    imgPath='/home/weixin_wechat/wp/__pycache__/Snipaste_2022-10-03_09-45-47.png'
    upload_images(imgPath)

报错处理:

{   'code': 'rest_upload_sideload_error',
    'data': {'status': 500},
    'message': '无法建立目录wp-content/uploads/2023/04。有没有上级目录的写权限?'}

解决方式:

1 .在WordPress数据库中找到表wp_options,修改upload_path的值为”wp-content/uploads”,注意带双引号

  1. 赋值权限: ```chmod 777 /var/www/wordpress/wp-content/uploads/2023/* ```` 注意*号

参考

如何在 python 中使用 wordpress REST api 上传图像? - 堆栈溢出

无法建立目录wp-content/uploads//。有没有上级目录的写权限?_无法创建目录 wp-content/uploads/2023/04。它的父目录是否可以被服务器写入?_ChijinLoujue的博客-CSDN博客

Solved:无法建立目录wp-content/uploads.有没有上级目录的写权限?_Jasonty的博客-CSDN博客

使用 WordPress REST API 上传特色图片以发布

posted @ 2023-04-17 22:12  ministep88  阅读(180)  评论(0)    收藏  举报
网站更新内容:请访问:https://bigdata.ministep.cn/