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

Tri*_*mas 3 python python-requests strapi

我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)

我尝试使用requests.post'sfiles参数代替's 参数data,但无法正常工作。另外,我也尝试过发帖/upload,但失败了。

Tri*_*mas 7

终于做到了...

要点是,您必须/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
Run Code Online (Sandbox Code Playgroud)

您的媒体现在应该位于 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)
Run Code Online (Sandbox Code Playgroud)