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)

执行结果:

相关推荐
观察员4 分钟前
用 Streamlit + 智谱 AI 打造虚拟伴侣聊天机器人
python
Cubar41 分钟前
[一]开源ERP:odoo19二次开发问题-原库存模块问题
python·开源·odoo·开源erp
滴滴滴嘟嘟嘟.1 小时前
强化学习-PPO 奖励塑形实验:Pendulum-v1 中角速度惩罚权重的影响
开发语言·python
Sylvia33.2 小时前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
lupai2 小时前
身份证二要素实名认证 API 落地应用指南
python
cxr8282 小时前
大语言模型上下文缓存命中率测试全场景清单
人工智能·python·算法·缓存·语言模型·自然语言处理·llm
某林2122 小时前
大模型边缘部署到底层硬件闭环
python·架构·机器人·硬件架构·ros2
编码者卢布2 小时前
【Azure Application Insights】公网白名单应用如何使用 Application Insights 可用性测试?
flask·azure·可用性测试
LadenKiller2 小时前
最新量化软件选择,先按能力判断表达生成和执行
人工智能·python
iuu_star3 小时前
Python大模型智能学习平台——设计与实现(AI教学系统)
大数据·人工智能·python·学习