简体   繁体   English

使用 Flask-marshmallow 和 flask-restful 发布复杂对象

[英]Post complex objects with Flask-marshmallow and flask-restful

I'm developing an API to learn Flask using flask-restful and flask-marshmallow and I would like to know if it's possible to post and serialize a list of complex objects at once.我正在开发一个 API 来使用flask-restful 和flask-marshmallow 来学习Flask,我想知道是否可以一次发布和序列化复杂对象的列表。

Here's my current code:这是我当前的代码:

class Post(db.Document):
    created_at = db.DateTimeField(default=datetime.now, required=True)
    title = db.StringField(max_length=255, required=True)
    slug = db.StringField(max_length=255, required=True)
    body = db.StringField(required=True)
    comments = db.ListField(db.EmbeddedDocumentField('Comment'))

    meta = {
        'allow_inheritance': True,
        'indexes': ['-created_at', 'slug'],
        'ordering': ['-created_at']
    }


class Comment(db.EmbeddedDocument):
    created_at = db.DateTimeField(default=datetime.now, required=True)
    body = db.StringField(verbose_name="Comment", required=True)
    author = db.StringField(verbose_name="Name", max_length=255, required=True)


class PostSerializer(Serializer):
    id = fields.String()
    class Meta:
        additional = ("created_at", "title", "slug", "body", "comments")


# just a test for multiple data
class PostViewList(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('posts', type = str, action='append',
                                   required = True, help = 'No posts given',
                                   location='json')

    def post(self):
        args = self.reqparse.parse_args()

        serializer = PostSerializer(many=True)
        result = serializer.load(args['posts'])

        return args["posts"], 201

api.add_resource(PostViewList, '/posts')

The way it is right now, I receive an error on "serializer.load" because the post is not treated as an object, but as a string.现在的方式是,我在“serializer.load”上收到一个错误,因为帖子不被视为对象,而是作为字符串。 If i dont try to serialize and return the "args['posts']" it show me the whole string I've posted.如果我不尝试序列化并返回“args['posts']”,它会显示我发布的整个字符串。

I tried post the following Json:我尝试发布以下 Json:

{"posts":[ { "title":"asd", "slug": "asd", "body" : "asd" }, { "title":"qwe", "slug": "qwe", "body" : "qwe" }]}

The way it is right now, I haven't sent yet a list of comments, because I can't even process just the process that I didn't tried.现在的情况,我还没有发送评论列表,因为我什至无法处理我没有尝试过的过程。

Ok, I've figured it out after a while.好的,我在一段时间后想通了。

I've implemented the make_object on the PostSerializer, and declared a serializer for the comment too, nested as many with the post:我已经在 PostSerializer 上实现了 make_object,并且也为评论声明了一个序列化器,嵌套在帖子中:

class CommentsSerializer(Serializer):
    class Meta:
        fields = ("created_at", "body", "author")

class PostSerializer(Serializer):
    id = fields.String()
    title = fields.String(required=True)
    comments = fields.Nested(CommentsSerializer, many=True)

    def make_object(self, data):
        return Post(**data)

    class Meta:
        additional = ("slug", "body", "created_at")

And then, on the post method, just got the json from flask, validated and serialized everything然后,在post方法上,从flask中获取json,验证并序列化所有内容

class PostViewList(Resource):
    def post(self):
        if not request.get_json():
            return bad_request('No input data provided')    
        content_input = request.get_json().get("posts")    
        serializer = PostSerializer(many=True)
        errors = serializer.validate(content_input)
        if errors:
            return jsonify(errors), 400    
        result = serializer.load(content_input)    
        r = Post.objects.insert(result.data)
        return PostSerializer(r, many=True).data, 201

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM