大型的互联网项目中,返回的数据格式,有时是比较复杂的结构。 如:豆瓣电影https://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=&start=20&limit=20返回的值里有 json 或者列表数据,这时可以通过以字段来实现fields.List 放置一个列表fields.Nested 放置一个字典
代码实现:
# flask_restful规范返回值之类型设置
from flask import Flask
from flask_restful import Api,Resource,fields,marshal_withapp = Flask(__name__)
api = Api(app)class User:def __init__(self,uname):self.uname = unamedef __repr__(self):return f'<User uname:{self.uname}>'class NewsType:def __init__(self,_type):self._type = _typedef __repr__(self):return f'<User type:{self._type}>'class News:def __init__(self,code,msg):self.code = codeself.msg = msgself.user = Noneself._type = []def __repr__(self):return f'<News code:{self.code} msg:{self.msg} user:{self.user} type:{self._type} >'def create_data():user = User('sxt')_type1 = NewsType('IT')_type2 = NewsType('Python')news = News(200,'python又更新了')news.user = usernews._type.append(_type1)news._type.append(_type2)return newsclass NewsView(Resource):resouce_fields = {'code':fields.Integer,'msg':fields.String,'user':fields.Nested({'uname':fields.String, }),'_type':fields.List(fields.Nested({'_type':fields.String}))}@marshal_with(resouce_fields)def get(self):news = create_data()return newsapi.add_resource(NewsView,'/news/')if __name__=="__main__":app.run(debug=True)
执行结果: