Post 使用 Flask-marshmallow 和 flask-restful 的复杂对象
Post complex objects with Flask-marshmallow and flask-restful
我正在开发一个 API 来使用 flask-restful 和 flask-marshmallow 来学习 Flask,我想知道是否可以 post 并序列化一个列表一次处理复杂的对象。
这是我当前的代码:
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')
现在的情况是,我在“serializer.load”上收到错误,因为 post 未被视为对象,而是被视为字符串。如果我不尝试序列化和 return “args['posts']”,它会显示我 posted.
的整个字符串
我尝试了post以下Json:
{"posts":[ { "title":"asd", "slug": "asd", "body" : "asd" }, { "title":"qwe", "slug": "qwe", "body" : "qwe" }]}
现在这样,我还没有发送评论列表,因为我什至不能只处理我没有尝试过的过程。
好的,我想了一会儿。
我已经在 PostSerializer 上实现了 make_object,并且也为评论声明了一个序列化程序,嵌套了与 post:
一样多的内容
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")
然后,在 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
我正在开发一个 API 来使用 flask-restful 和 flask-marshmallow 来学习 Flask,我想知道是否可以 post 并序列化一个列表一次处理复杂的对象。
这是我当前的代码:
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')
现在的情况是,我在“serializer.load”上收到错误,因为 post 未被视为对象,而是被视为字符串。如果我不尝试序列化和 return “args['posts']”,它会显示我 posted.
的整个字符串我尝试了post以下Json:
{"posts":[ { "title":"asd", "slug": "asd", "body" : "asd" }, { "title":"qwe", "slug": "qwe", "body" : "qwe" }]}
现在这样,我还没有发送评论列表,因为我什至不能只处理我没有尝试过的过程。
好的,我想了一会儿。
我已经在 PostSerializer 上实现了 make_object,并且也为评论声明了一个序列化程序,嵌套了与 post:
一样多的内容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")
然后,在 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