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)

执行结果:

相关推荐
zyq99101_116 分钟前
Python日期处理实战代码
python·算法·蓝桥杯
24kHT18 分钟前
tensorboard——SummaryWriter
python
高洁0120 分钟前
数据可视化实战:用AI工具制作专业数据分析图表
人工智能·python·深度学习·信息可视化·transformer
夏星印37 分钟前
argparse解析器参数详解
经验分享·笔记·python·学习·argparse
码喽7号1 小时前
springboot学习四:RESTful风格+swagger
spring boot·学习·restful
鬓戈1 小时前
SeaweedFS集群上文件遍历和删除
运维·python
困死,根本不会3 小时前
蓝桥杯python备赛笔记之(十)数论基础 & 日期问题
笔记·python·蓝桥杯
輕華3 小时前
Python 命令行参数处理:sys.argv 与 argparse 深度对比
python
清水白石0084 小时前
Python 内存陷阱深度解析——浅拷贝、深拷贝与对象复制的正确姿势
开发语言·python
国家二级编程爱好者4 小时前
删除typora文档没有引用的资源文件
git·python