我有一个小的Python/Flask应用程序,应该将图片存储在MongoDB中。
- 客户端提交HTTP POST(JSON),其中一个字段是base64编码的图像。
- 服务器应该将这个图像存储在MongoDB ImageField中。我现在正在使用mongoengine。
模型:
class Image(db.EmbeddedDocument):
data = db.ImageField()
现在,相关的服务器代码看起来像这样:
import Image as PIL
import base64
import cStringIO # I'm trying to give PIL something that can handle common file operations without having to write to disk
imageData = jsondata['image']
file_like = cStringIO.StringIO(base64.decodestring(imageData))
PILImage = PIL.open(file_like)
# new mongo object
img = Image(name="imagename")
img.data = PILImage # assignment of image data
img.save()
这给了我一个错误 #=>ValidationError: ValidationError (位置: 53e37ed6844de403e0998182) (image.grid_id: ['images'])
当我将图像数据的赋值更改为以下内容时:
img.data.put(PILImage)
我会尽力为您翻译。这是需要翻译的内容:
我得到了一个错误:# => 验证错误:无效图像:read
因此,我认为它可能正在寻找支持“read”方法的对象。当我将赋值更改为以下内容时:
img.data.put(file_like)
我遇到了错误:#=>“ValidationError:Invalid image:cannot identify image file”。我可以将数据进行base64编码,json.loads(),POST,json.dumps(), base64decode,并创建一个PIL图像。但是,MongoDB的ImageField无法将其识别为图像。有人能帮忙吗?需要注意的一件事是:如果我只是将PILImage直接写入磁盘,然后通过告知mongoengine进行存储...
img.data.put("path/to/image/file")
我可以解决这个问题,但我希望避免文件系统操作,因为我们预计应用程序将经历相当大量的流量,并且我们怀疑IO将是第一个瓶颈。