如何使用 Python 请求将图像发送到 Strapi?

How to send image to Strapi with Python Requests?

我正在尝试使用 Python 请求将图像/文件发送到 Strapi 集合类型?

我有一个名为 log 的集合类型,它有一个媒体(和两个文本字段)。我不知道如何使用图像创建新的 log

我只是在混搭代码,但这就是我目前所拥有的(我正在尝试使图像流化,希望它能起作用):

import requests
from utils.networking import LOCAL, PORT

import io
import numpy as np
import matplotlib.pyplot as plt

# I converted the image from numpy array to png
buf = io.BytesIO()
plt.imsave(buf, cvimage, format='png')
image = buf.getvalue()

payload = {
    "Type": 'info'
    "Message": 'Testing',
}

req = requests.post(f'http://localhost:1337/logs', json=payload, data=image)

我试过使用 requests.postfiles 参数而不是 data,但我无法正常工作。另外,我也试过发帖到 /upload,但失败了。

首先你应该 post 你的文件到 /upload/ 端点,你的正文必须是 form-data 并且在 postman 中具有以下值例如:

KEY : files 
VALUE : "The file you want to save"

注意,KEY 值必须始终为 files,然后响应将如下所示:

[
    {
        "_id": "5f38db271f720e3348b75327",
        "name": "testImage",
        "alternativeText": null,
        "caption": null,
        "hash": "testImage_d12913636e",
        "ext": ".jpeg",
        "mime": "image/jpeg",
        "size": 18.4,
        "width": 512,
        "height": 213,
        "url": "/uploads/testImage_d12913636e.jpeg",
        "formats": {
            "thumbnail": {
                "hash": "thumbnail_testImage_d12913636e",
                "ext": ".jpeg",
                "mime": "image/jpeg",
                "width": 245,
                "height": 102,
                "size": 5.03,
                "path": null,
                "url": "/uploads/thumbnail_testImage_d12913636e.jpeg"
            },
            "small": {
                "hash": "small_testImage_d12913636e",
                "ext": ".jpeg",
                "mime": "image/jpeg",
                "width": 500,
                "height": 208,
                "size": 17.03,
                "path": null,
                "url": "/uploads/small_testImage_d12913636e.jpeg"
            }
        },
        "provider": "local",
        "related": [],
        "createdAt": "2020-08-16T07:07:19.355Z",
        "updatedAt": "2020-08-16T07:07:19.355Z",
        "__v": 0,
        "id": "5f38db271f720e3348b75327"
    }
]

然后每当你想将图片或文件设置到一个字段时,你只需要使用上面响应的id

终于做到了...

要点是,您必须先将图像/文件上传到/upload。然后,要将媒体添加到集合类型条目中,请在媒体字段中引用您刚刚上传的 id

像这样上传媒体:

import requests
import json

files = {'files': ('Screenshot_5.png', open('test.jpeg', 'rb'), 'image', {'uri': ''})}
response = requests.post('http://localhost:1337/upload', files=files)

print(response.status_code)
# `response.text` holds the id of what you just uploaded

您的媒体现在应该在 Strapi 媒体库中(您应该 double-check 这个)。

最后,现在您可以创建一个条目(像往常一样)并使用您上传的内容的 id 添加媒体。

payload = {
    "Type": 'info',
    "Message": 'lorem ipsum beep bop',
    "Screenshot": 1, # this is the id of the media you uploaded
}
response = requests.post('http://localhost:1337/logs', json=payload)

print(response.status_code)

在 Strapi 版本 3 中,如屏幕截图所示编写邮递员请求,然后转到代码部分以在邮递员中自动生成代码 postman request screenshot