在使用flask_restful进行开发类视图函数的时候,需要自定义序列化规则。
两种方式:
class Coo(fields.Raw):
def format(self, start_time):
"""重写format函数,将时间返回改成:年-月"""
time_ = start_time.strftime('%Y-%m')
return time_
fields = { # 序列化规则
'username': fields.String(attribute='name'), # 指定对应的模型属性
'age': fields.Integer(default=10), # 设置默认值
'height': fields.Float,
'scores': fields.List(fields.Integer),
# 方案一:自定义类规则
'start_time': Coo(attribute='start_time'), #Coo类为自定义的序列化规则
# 方案二:在attribute属性中自定义规则
'start_time': fields.String(attribute=lambda t:t.start_time.strftime('%Y-%m') if t.start_time else None),
}
class DemoResource(Resource):
method_decorators = {'post': [marshal_with(fields)]}
def post(self):
user1 = User()
# 如果设置了marshal_with装饰器, 可以直接返回模型对象
return user1