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)

执行结果:

相关推荐
m0_748252384 分钟前
Ruby 模块(Module)的基本概念
开发语言·python·ruby
子午12 分钟前
【2026原创】水稻植物病害识别系统~Python+深度学习+人工智能+resnet50算法+TensorFlow+图像识别
人工智能·python·深度学习
深蓝电商API15 分钟前
Scrapy ImagesPipeline和FilesPipeline自定义使用
爬虫·python·scrapy
木卫二号Coding18 分钟前
Python-文件拷贝+文件重命名+shutil+记录
开发语言·python
爬山算法37 分钟前
Hibernate(44)Hibernate中的fetch join是什么?
前端·python·hibernate
一代明君Kevin学长1 小时前
记录一个上手即用的Spring全局返回值&异常处理框架
java·网络·python·spring
教游泳的程序员1 小时前
【面试问题精选】java开发工程师
python·面试·职场和发展
爬山算法1 小时前
Hibernate(43)Hibernate中的级联删除如何实现?
java·python·hibernate
Stream_Silver1 小时前
【安装与配置Anaconda步骤,包含卸载重装】
python·conda
ai_top_trends1 小时前
AI 生成 PPT 工具横评:效率、质量、稳定性一次说清
人工智能·python·powerpoint