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

2024-03-28 17:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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发帖,但失败了


Tags: fromio图像imageimportnumpylog类型
2条回答

终于做到了

要点是,您必须首先将图像/文件上载到/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媒体库中(您应该仔细检查)

最后,现在您可以创建一个条目(正如您通常所做的那样)并使用您上传到添加媒体的内容的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)

首先,您应该将文件发布到/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

相关问题 更多 >