flask_restful规范返回值之类型设置

大型的互联网项目中,返回的数据格式,有时是比较复杂的结构。 如:豆瓣电影
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_with

app = Flask(__name__)
api = Api(app)

class User:
    def __init__(self,uname):
        self.uname = uname

    def __repr__(self):
        return f'<User uname:{self.uname}>'

class NewsType:
    def __init__(self,_type):
        self._type = _type
    
    def __repr__(self):
        return f'<User type:{self._type}>'

class News:
    def __init__(self,code,msg):
        self.code = code
        self.msg = msg
        self.user = None
        self._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 = user
    news._type.append(_type1)
    news._type.append(_type2)

    return news

class 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 news

api.add_resource(NewsView,'/news/')

if __name__=="__main__":
    app.run(debug=True)

执行结果:

相关推荐
AI手记叨叨17 小时前
Python数学:几何运算
python·数学·解析几何·射影几何·微分几何·欧几里得几何
toolhow18 小时前
SelfAttenion自注意力机制
pytorch·python·深度学习
智航GIS18 小时前
6.2 while循环
java·前端·python
qq_3363139318 小时前
java基础-IO流(转换流)
java·开发语言·python
Stestack18 小时前
ssh批量机器免密操作
linux·python·ssh
a程序小傲18 小时前
得物Java面试被问:反射机制的原理和应用场景
java·python·面试
于越海18 小时前
学习小项目:用 Python 自动统计编程课绩点(5.0 制|百分制直算|重修取最高)
开发语言·笔记·python·学习·学习方法
xingzhemengyou118 小时前
Python GUI中常用的after
开发语言·python
郝学胜-神的一滴18 小时前
Python抽象基类与abc模块详解:优雅设计接口的利器
开发语言·python·程序人生
小南知更鸟18 小时前
前端静态项目快速启动:python -m http.server 4173 与 npx serve . 全解析
前端·python·http