简体   繁体   English

如何在python中使用wordpress REST api上传图片?

[英]How to upload images using wordpress REST api in python?

I think I've got this 90% working, but it ends up 'uploading' a blank transparent image.我想我已经完成了 90% 的工作,但它最终“上传”了一张空白的透明图像。 I get a 201 response after the upload.上传后我收到 201 响应。 I think that's probably a proxy for when WP finds a missing image.我认为这可能是 WP 找到丢失图像的代理。 I'm unsure if i'm passing the image incorrectly (ie it doesn't leave my computer) or if I'm not tagging it properly to WP's liking.我不确定我是否错误地传递了图像(即它没有离开我的电脑)或者我是否没有按照 WP 的喜好正确标记它。

from base64 import b64encode
import json
import requests

def imgUploadREST(imgPath):
    url = 'https://www.XXXXXXXXXX.com/wp-json/wp/v2/media'
    auth = b64encode('{}:{}'.format('USERNAME','PASS'))
    payload = {
        'type': 'image/jpeg',  # mimetype
        'title': 'title',
        "Content":"content",
        "excerpt":"Excerpt",
    }
    headers = {
        'post_content':'post_content',
        'Content':'content',
        'Content-Disposition' : 'attachment; filename=image_20170510.jpg',
        'Authorization': 'Basic {}'.format(auth),
    }
    with open(imgPath, "rb") as image_file:
        files = {'field_name': image_file}
        r = requests.post(url, files=files, headers=headers, data=payload) 
        print r
        response = json.loads(r.content)
        print response
    return response

I've seen a fair number of answers in php or node.js, but I'm having trouble understanding the syntax in python. Thank you for any help!我在 php 或 node.js 中看到了相当多的答案,但我无法理解 python 中的语法。感谢您的帮助!

I've figured it out!我想通了!

With this function I'm able to upload images via the WP REST api to my site ( Photo Gear Hunter. ) The function returns the ID of the image.使用此功能,我可以通过 WP REST api 将图像上传到我的站点( Photo Gear Hunter。 )该函数返回图像的 ID。 You can then pass that id to a new post call and make it the featured image, or do whatever you wish with it.然后,您可以将该 id 传递给新的 post call 并将其设为特色图像,或者使用它做任何您想做的事情。

def restImgUL(imgPath):
    url='http://xxxxxxxxxxxx.com/wp-json/wp/v2/media'
    data = open(imgPath, 'rb').read()
    fileName = os.path.basename(imgPath)
    res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
                        data=data,
                        headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName},
                        auth=('authname', 'authpass'))
    # 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)

An improved version to handle non-ASCII in the filename (Greek letters for example).处理文件名中的非 ASCII的改进版本(例如希腊字母)。 What it does is convert all non-ASCII characters to a UTF-8 escape sequence.它的作用是将所有非 ASCII 字符转换为 UTF-8 转义序列。 (Original code from @my Year Of Code ) (来自@my Year Of Code 的原始代码)

def uploadImage(filePath):
    data = open(filePath, 'rb').read()
    
    fileName = os.path.basename(filePath)
    
    espSequence = bytes(fileName, "utf-8").decode("unicode_escape")  
    # Convert all non ASCII characters to UTF-8 escape sequence

    res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
                        data=data,
                        headers={'Content-Type': 'image/jpeg',
                                 'Content-Disposition': 'attachment; filename=%s' % espSequence,
                                 },
                        auth=('authname', 'authpass'))
    newDict=res.json()
    newID= newDict.get('id')
    link = newDict.get('guid').get("rendered")
    print newID, link
    return (newID, link)

From my understading a POST HEADER can only containg ASCII characters据我了解,POST HEADER 只能包含 ASCII 字符

To specify additional fields supported by the api such as alt text, description ect:要指定 api 支持的其他字段,例如 alt 文本、描述等:

from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import os
fileName = os.path.basename(imgPath)
multipart_data = MultipartEncoder(
    fields={
        # a file upload field
        'file': (fileName, open(imgPath, 'rb'), 'image/jpg'),
        # plain text fields
        'alt_text': 'alt test',
        'caption': 'caption test',
        'description': 'description test'
    }
)

response = requests.post('http://example/wp-json/wp/v2/media', data=multipart_data,
                         headers={'Content-Type': multipart_data.content_type},
                         auth=('user', 'pass'))

thanks to @my Year Of Code .感谢@my Year Of Code

my final working code:我的最终工作代码:

import 
HOST = "https://www.crifan.com"
API_MEDIA = HOST + "/wp-json/wp/v2/media"
JWT_TOKEN = "eyJxxxxxxxxjLYB4"

    imgMime = gImageSuffixToMime[imgSuffix] # 'image/png'
    imgeFilename = "%s.%s" % (processedGuid, imgSuffix) # 'f6956c30ef0b475fa2b99c2f49622e35.png'
    authValue = "Bearer %s" % JWT_TOKEN
    curHeaders = {
        "Authorization": authValue,
        "Content-Type": imgMime,
        'Content-Disposition': 'attachment; filename=%s' % imgeFilename,
    }
    # curHeaders={'Authorization': 'Bearer eyJ0xxxyyy.zzzB4', 'Content-Type': 'image/png', 'Content-Disposition': 'attachment; filename=f6956c30ef0b475fa2b99c2f49622e35.png'}
    uploadImgUrl = API_MEDIA
    resp = requests.post(
        uploadImgUrl,
        # proxies=cfgProxies,
        headers=curHeaders,
        data=imgBytes,
    )

return 201 means Created OK返回201表示Created OK

response json look like:响应 json 看起来像:

{
  "id": 70393,
  "date": "2020-03-07T18:43:47",
  "date_gmt": "2020-03-07T10:43:47",
  "guid": {
    "rendered": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png",
    "raw": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png"
  },
...

more details refer my (Chinese) post: 【已解决】用Python通过WordPress的REST API上传图片更多详情参考我的(中文)帖子: 【已解决】用Python通过WordPress的REST API上传图片

This is my working code for uploading image into WordPress from local image or from url.这是我从本地图像或 url 将图像上传到 WordPress 的工作代码。 hope someone find it useful.希望有人觉得它有用。

import requests, json, os, base64

def wp_upload_image(domain, user, app_pass, imgPath):
    # imgPath can be local image path or can be url
    url = 'https://'+ domain + '/wp-json/wp/v2/media'
    filename = imgPath.split('/')[-1] if len(imgPath.split('/')[-1])>1 else imgPath.split('\\')[-1]
    extension = imgPath[imgPath.rfind('.')+1 : len(imgPath)]
    if imgPath.find('http') == -1:
        try: data = open(imgPath, 'rb').read()
        except:
            print('image local path not exits')
            return None
    else:
        rs = requests.get(imgPath)
        if rs.status_code == 200:
            data = rs.content
        else:
            print('url get request failed')
            return None
    headers = { "Content-Disposition": f"attachment; filename={filename}" , "Content-Type": str("image/" + extension)}
    rs = requests.post(url, auth=(user, app_pass), headers=headers, data=data)
    print(rs)
    return (rs.json()['source_url'], rs.json()['id'])

import base64
import os

import requests

def rest_image_upload(image_path):
    message = '<user_name>' + ":" + '<application password>'
    message_bytes = message.encode('ascii')
    base64_bytes = base64.b64encode(message_bytes)
    base64_message = base64_bytes.decode('ascii')

    # print(base64_message)

    data = open(image_path, 'rb').read()
    file_name = os.path.basename(image_path)
    res = requests.post(url='https://<example.com>/wp-json/wp/v2/media',
                    data=data,
                    headers={'Content-Type': 'image/jpg',
                             'Content-Disposition': 'attachment; filename=%s' % file_name,
                             'Authorization': 'Basic ' + base64_message})
    new_dict = res.json()
    new_id = new_dict.get('id')
    link = new_dict.get('guid').get("rendered")
    # print(new_id, link)
    return new_id, link

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用元数据将文件上传到 SharePoint - how to upload file to SharePoint with Metadata using Python Rest API 如何在 Python 中使用 Wordpress Rest-Api 填充 ACF 字段 - How to fill ACF fields using Wordpress Rest-Api in Python 使用 Python 和 REST API 将图片上传到 Shopify - Upload image to Shopify using Python and REST API 使用Python API将图片异步上传到Cloudinary - Asynchronously upload images to Cloudinary using the Python API 如何在 Python 中使用 wordpress api 上传图像? - How to upload an image with the wordpress api in Python? 如何使用具有上传权限的API密钥上传图像? [包含Python源代码] - How to upload images using an API Key that gives you permission to upload? [Python source code included] 如何使用 Python 中的 REST API 在 GCS 存储桶中上传带有自定义元数据的文件 - How to upload file with custom metadata in GCS bucket using REST API in Python 如何使用REST Api / JSON对象和python将子页面上传到Confluence? - How to upload Child page to Confluence using REST Api/JSON object with python? 使用REST API python将页面Blob上传到Azure - upload a page blob to azure using REST API python 使用Rest API Python进行Tableau下载/导出图像 - Tableau download/export images using Rest api python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM