如何使用flask-restplus的fields.Url用于mongoengine文档查询集?

时间:2019-10-24 10:02:48

标签: python flask marshalling mongoengine flask-restplus

我有以下Mongoengine Document

class Post(mongo_db.Document):
    id = mongo_db.UUIDField(max_length=300, required=True, primary_key=True)
    content = mongo_db.StringField(max_length=300, required=False,)
    notes = mongo_db.ListField(mongo_db.StringField(max_length=2000), required=False)
    category = mongo_db.ReferenceField('Category', required=True)
    creation_date = mongo_db.DateTimeField()

以及以下model,为其定义的资源:

post_fields = ns.model(
    'Post', 
    {
        'content': fields.String,
        'creation_date': fields.DateTime,
        'notes': fields.List(fields.String),
        'category': fields.Nested(category_fields),
        'URI': fields.Url('my_endpoint')
    }
)


class PostResource(Resource):

    @ns.marshal_with(post_fields)
    def get(self):
        queryset = Post.objects
        return list(queryset)

除fields.Url外,所有字段对所有字段均正常运行,并引发以下错误:

flask_restplus.fields.MarshallingError: url_for() argument after ** must be a mapping, not Post

我尝试使用flask的{​​{1}}函数:

jsonify

但发生以下错误:

return jsonify(queryset)

如果您需要其他任何详细信息,请通知我。

1 个答案:

答案 0 :(得分:1)

我尝试通过简化Documentmodel来解决您的问题。问题出在您的资源的响应上:

def get(self):
        queryset = Post.objects
        return list(queryset)

queryset成为帖子列表,形式为[<Post: Post object>, <Post: Post object>]。  将marshal_with装饰器应用于响应时,它会expects single object, dicts, or lists of objects。尽管它可以与Post对象一起使用,但是我不确定直接将URI应用于Post对象时是什么导致错误。似乎以某种方式在内部调用了url_for方法及其适当的参数,并试图将Post对象解压缩为**post

小例子:

def url_for(endpoint, *args, **kwargs):
    print(endpoint, args, kwargs)

class Post:

    def __init__(self):
        self.content = "Dummy content"

post1 = Post()  # Instance of Post class
post2 = {"content": "This dummy content works !"} # Dictionary

# This won't work, returns TypeError: url_for() argument after ** must be a mapping, not Post
url_for("my_endpoint", 1, 2, **post1)

# This works since it's able to unpack dictionary.
url_for("my_endpoint", 1, 2, **post2)

解决方案是通过在其上使用Post将每个dict对象转换为.to_mongo().to_dict()。另外,要用ID表示对象Post的URI,我们必须为其创建资源路由。

完整示例:

from flask import Flask
from flask_restplus import Api, fields, Resource, marshal_with
from flask_mongoengine import MongoEngine

import uuid

app = Flask(__name__)
api = Api(app)

app.config['MONGODB_SETTINGS'] = {
    'db': 'test',
    'host': 'localhost',
    'port': 27017
}

mongo_db = MongoEngine(app)

class Post(mongo_db.Document):
    id = mongo_db.UUIDField(max_length=300, required=True, primary_key=True)
    content = mongo_db.StringField(max_length=300, required=False)
    notes = mongo_db.ListField(mongo_db.StringField(max_length=2000), required=False)

#post1 = Post(id=uuid.uuid4(), content="abacdcad", notes=["a", "b"])
#post2 = Post(id=uuid.uuid4(), content="aaaaa", notes=["a", "bc"])

#post1.save()
#post2.save()

post_fields = {
    'content': fields.String,
    'notes': fields.List(fields.String),
    'URI': fields.Url('my_endpoint')
}

class PostResource(Resource):
    @marshal_with(post_fields)
    def get(self):
        queryset = [obj.to_mongo().to_dict() for obj in Post.objects]
        return queryset


class PostEndpoint(Resource):

    def get(self, _id):
        # Query db for this entry.
        return None


api.add_resource(PostResource, '/posts')
api.add_resource(PostEndpoint, '/post/<string:_id>', endpoint='my_endpoint')

if __name__ == '__main__':
    app.run(debug=True)

请注意,_id代表文档中的id条目。 Mongoengine这样返回它,不确定原因。也许主键前面带有下划线。

http://127.0.0.1:5000/posts的响应应该是( URI来自我的示例):

[
  {
    "content": "Dummy content 1",
    "notes": [
      "a",
      "b"
    ],
    "URI": "/post/0b689467-41cc-4bb7-a606-881f6554a6b7"
  },
  {
    "content": "Dummy content 2",
    "notes": [
      "c",
      "d"
    ],
    "URI": "/post/8e8c1837-fdd2-4891-90cf-72edc0f4c19a"
  }
]

我希望这可以解决问题。