如何使用flask-restplus的字段。mongoengine文档查询集的网址?

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

我有以下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

我尝试使用flaskjsonify函数:

return jsonify(queryset)

但是发生以下错误:

werkzeug.routing.BuildError: Could not build url for endpoint 'my_endpoint' with values ['_on_close', '_status', '_status_code', 'direct_passthrough', 'headers', 'response']. Did you forget to specify values ['id']?

如果需要其他详细信息,请告知我,并提前致谢。

python flask marshalling mongoengine flask-restplus
1个回答
0
投票

我尝试通过简化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"
  }
]

我希望这可以解决问题。

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