如何使用MongoEngine从参考字段中检索pdf /图像?

问题描述 投票:1回答:1

我在检索使用mongodb的flask的类引用的pdf /图像文件时遇到了一些困难。例如,我有这个模型:

class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.ReferenceField('fs.files')
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

Users表中记录的JSON如下所示:

{
    "_id": "1", 
    "name": "John Doe", 
    "picture": {
        "$ref": "fs.files", 
        "$id": {
            "$oid": "5e1...a932"
         }
     }, 
     "email":"[email protected]", 
     "password": "12345"
}

[在Flask Restful api中使用此模型,我试图检索与用户关联的图像以显示在我的应用程序中。另外,添加新用户后,如何在用户表中保存带有引用的文件?图像的参考存储在图片字段中。我也想以相同的方式对pdf执行此操作。

我尝试查看GridFS,但我不太了解它的工作方式或如何在mongoengine的flask API中实现它。谢谢。

python mongodb mongoengine flask-restful flask-mongoengine
1个回答
0
投票

您可以使用Flask的send_file扩展名来创建将静态文件作为响应加载的URL。

from flask import send_file

@app.route('/get-image/<user>')
def get-image(user):
    """Serves static image loaded from db."""

    user = Users.objects(name=user).first()

    return send_file(io.BytesIO(user.picture.read()),
                     attachment_filename='image.jpg',
                     mimetype='image/jpg')

为了使上述解决方案生效,您应该在文档模型上使用FileField()而不是ReferenceField()-使用GridFS:

class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.FileField()
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

您可以像这样将文件加载到模型中:

user = Users.objects(name='User123').first()

with open('pic.jpg', 'rb') as fd:
    user.picture.put(fd, content_type = 'image/jpeg')
user.save()

希望它很适合您

http://docs.mongoengine.org/guide/gridfs.html

© www.soinside.com 2019 - 2024. All rights reserved.