json如何使用postman上传DBRef数据?

How to use postman to upload DBRef data in json?

我正在尝试使用 postman post 数据到 mongodb,但我不知道在 [=] 中上传对图像文件的引用的正确约定27=] 桶。基本上,该文件已经在数据库中,我只是想 post 一个新用户引用该图像。

这是我的模型:

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

在 postman 中,我尝试像这样 post 数据:

{
"_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" : "example@example.com"
}

我正在使用 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'])

如何在 postman 中 post 新用户?感谢您的帮助

您需要稍微更改一下代码

添加这些导入:

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

修改您的 class picture 字段定义 + 添加额外的 class 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()

这是一个验证错误。数据库接受的 JSON 格式比我 posting 的格式要特殊。而且我处理 post 请求的方式也不正确。这是它期望的格式:

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

Postman 无法接受上述格式,而是接受了以下格式:

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

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

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

然后瞧,成功了!