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)

执行结果:

相关推荐
ValhallaCoder6 小时前
Leetcode-hot100(2026.08.17)
python·算法·leetcode
W_326006 小时前
Python-OpenCV图像像素与通道:通道拆分合并、深浅拷贝
图像处理·人工智能·python·opencv·机器学习
让你三行代码QAQ6 小时前
AI大模型开发核心名词速览
python
2401_868534787 小时前
农商行分布式网络建设
python·pygame
AC赳赳老秦8 小时前
OpenClaw 多源采集公开行业数据:从原始信息到研究报告初稿的自动化实践
java·c语言·c++·python·php·deepseek·openclaw
程序员雷欧8 小时前
AQS深度解析
开发语言·python
玩三国杀玩的8 小时前
Pytorch-c++-CUDA
c++·pytorch·python·深度学习
Albert Edison8 小时前
PyCharm 字体大小设置
ide·python·pycharm
叠层归一研究院8 小时前
如何用程序搭建一个 AGI 种子系统(一):从向量种子到无限生长引擎
人工智能·python·算法·机器学习·agi
l1258659 小时前
# RAG重排序实战:硅基流动bge-reranker-v2-m3在线API vs 本地CrossEncoder,一篇讲透两种方案
数据库·人工智能·python·深度学习·算法·机器学习·langchain