Как я могу это сделать без цикла?
Я думаю, что это возможно, потому что возврат изображений просто работает.
Код: Выделить всё
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
import json
app = FastAPI()
class Image(BaseModel):
url: str
name: str
@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):
#return images # returns json string
#print(images) # prints an Image object
#print(images.json()) # AttributeError: 'list' object has no attribute 'json'
#print(json.dumps(images)) # TypeError: Object of type Image is not JSON serializable
img_data = list() # does it really have to be this way?
for i in images:
img_data.append(i.dict())
with open('./images.json', 'w') as f:
json.dump(img_data, f, indent=2)
'''
curl -v -d '[{"name":"wilma","url":"http://this.com"},{"name":"barney","url":"http://that.com"}]' http://localhost:8000/images/multiple/
'''
Подробнее здесь: https://stackoverflow.com/questions/649 ... ted-models