如何使用邮递员在json中上传DBRef数据?

问题描述 投票:0回答:2

我正在尝试使用邮递员将数据发布到mongodb,但我不知道将引用上传到fs.files存储桶中图像文件的正确约定。基本上,该文件已经在数据库中,我只是想发布一个引用该图像的新用户。

这是我的模特:

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

在邮递员中,我尝试像这样发布数据:

{
"_id" : "1",
"name" : "John Doe",
"picture": [{"$id": "5e6a...f9q102"}], #This is the reference id for the image already in the database, in fs.files
"password" : "<hashed pw>",
"email" : "[email protected]"
}

我正在使用flask restful api,因此在python脚本中,post函数的定义如下:

def post(self):
    body = request.get_json()
    print (body)
    user = Users()
    user = Users(**body).save()
    return 'Successful Upload', 200

尝试上述约定时出现错误:

mongoengine.errors.ValidationError: ValidationError (Users:None) ('list' object has no attribute
    'grid_id': ['picture'])

如何在邮递员中发布新用户?感谢您的帮助

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

您需要稍微更改一下代码

添加这些导入:

from mongoengine.fields import ImageGridFsProxy
from mongoengine import ReferenceField, DynamicDocument
from bson.dbref import DBRef
from bson import ObjectId

修改您的课程picture字段定义+添加额外的课程fs

class Fs(DynamicDocument):
    #Add 'db_alias':'default' to meta
    meta = {'collection': 'fs.files'}

class Users(Document):
    ...
    picture = ReferenceField('Fs', dbref=True)
    ...

现在,您需要通过以下方式为DBRef创建新实例:

def post(self):
    body = request.get_json()
    body["picture"] = DBRef('fs.files', ObjectId(body["picture"]))

    #mongoengine assumes `ObjectId('xxx')` already exists in `fs.files`. 
    #If you want to check, run below code:
    #if Fs.objects(_id=body["picture"].id).first() is None:
    #    return 'Picture ' + str(body["picture"].id) + ' not found', 400

    user = Users(**body).save()
    return 'Successful Upload', 200

最后,如果您需要阅读图片内容:

image = ImageGridFsProxy(grid_id=ObjectId('xxx'))
f = open("image.png", "wb")
f.write(image.read())
f.close()

0
投票

这是验证错误。数据库正在接受比我发布的格式更特殊的JSON。而且我处理帖子请求的方式也不正确。这是预期的格式:

{
    ...,
    "picture" = {"$ref": "fs.files", 
                 "$id": ObjectId("5e6a...f9q102")},
    ...
}

邮递员不能接受上述格式,而是接受了此格式:

{
    "_id" : "1",
    "name" : "John Doe",
    "picture": {"$ref": "fs.files", "$id": {"$oid": "5e6a...f9q102"}}, 
    "password" : "<hashed pw>",
    "email" : "[email protected]"
}

为了完成这项工作,我更改了模型以使其在烧瓶应用程序中看起来像这样:

class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.ReferenceField('fs.files') #I changed this to a reference field because it holds the reference for the file and not the actual file in the database
    upload_picture = db.FileField() #I added this field so I can still upload pics via flask and via this document
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

然后,我不得不添加此导入并更改代码,以便它将输入读取为JSON并将图片的参考值传输到ObjectId(id),以使其与数据库期望的格式匹配。

from bson.json_util import loads

def post(self):
        body = str(request.get_json())
        x = body.replace("'", '"') #replace single quotes as double quotes to match JSON format
        data = loads(x)
        officer = Officers(**data).save()
        return 'Successful Upload', 200

然后瞧,它起作用了!

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