我正在构建简单的API,该API从url获取图像并将其存储在mongodb中。用户发送URL到API以提交新任务。然后,用户可以通过POST
方法检查任务状态并获取获取的图像列表:
def get_image_task(self, task_id):
try:
return ImageTask.objects.get(task_id=task_id)
except ImageTask.DoesNotExist:
return None
def post(self):
'''
Get status of submitted task.
'''
json_data = api.payload
task_id = json_data['task_id']
image = self.get_image_task(task_id)
if not image:
abort(404, 'Task does not exist.')
celery_task = AsyncResult(image.task_id)
image.task_status = celery_task.state
image.save()
return ImagePOSTOutput.dump(image)
这是我的ImageTask
和Image
的模型:
from flask_mongoengine import Document
from mongoengine import (
EmbeddedDocument,
StringField,
IntField,
BinaryField,
EmbeddedDocumentField,
ListField,
)
class Image(EmbeddedDocument):
id = IntField()
img = BinaryField()
class ImageTask(Task):
images = ListField(EmbeddedDocumentField(Image))
@classmethod
def pre_save(cls, sender, document, **kwargs):
if not document.task_id:
celery_task = get_images.apply_async((document.url, ))
document.task_id = celery_task.id
document.task_status = celery_task.state
这是我的序列化器:
from marshmallow_mongoengine import ModelSchema
from .models import ImageTask, Image
class ImageSchema(ModelSchema):
'''
Embedded image schema for Image model.
'''
class Meta:
model = Image
exclude = ('img', )
class ImageTaskSchema(ModelSchema):
'''
ImageTaskSchema schema for generating JSON response
based on ImageTask model.
'''
images = ImageSchema(many=True)
class Meta:
model = ImageTask
# PUT /images endpoint request and response schemas
ImagePUTInput = ImageTaskSchema(only=('url', ))
ImagePUTOutput = ImageTaskSchema(only=(
'task_id',
'task_status',
))
# POST /images endpoint request and response schemas
ImagePOSTInput = ImageTaskSchema(only=('task_id', ))
ImagePOSTOutput = ImageTaskSchema(only=('task_id', 'task_status', 'images.id'))
现在,提交新任务后,我发送POST
请求以获取图像列表并获得以下响应:
{
"task_status": "SUCCESS",
"task_id": "556f5b48-16fd-4775-aabf-a8fb14df0d08",
"images": {
"id": 0
}
}
图像列表显示,只有一幅图像被提取并保存到数据库中,尽管MongoDb显示为该任务存储了多个图像:
我正在关注官方Marshamallow docs,因此我的ImagePOSTOutput
序列化程序仅在json结果中返回id
,如schema = SiteSchema(only=['blog.author.email'])
所示。
我还尝试删除了only
的{{1}}参数,但是随后响应不包含图像列表:
ImagePOSTOutput
问题:为什么棉花糖只序列化{
"task_status": "SUCCESS",
"task_id": "556f5b48-16fd-4775-aabf-a8fb14df0d08"
}
中的一个嵌入式文档,而忽略所有剩余的嵌入式文档?我忘了做什么?
P.S:我正在使用Marshamllow-Mongoengine进行对象序列化。