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)

执行结果:

相关推荐
coder_Eight13 小时前
从 3 天到 8 分钟:我如何把垂直科普内容做成了自动化流水线
python·ai编程
水獭比特13 小时前
MCP SDK v2 迁移别只改依赖:先把 FastMCP 3/4 拆成两条测试线
人工智能·python
l12586513 小时前
# RAG多轮对话检索设计:Query重写如何让“那它呢“变成完整问题
前端·数据库·人工智能·python·算法·fastapi·milvus
dorky-org13 小时前
03-Python基础
python·具身智能
如此这般英俊13 小时前
手搓Claude Code-第十三章 background_tasks
前端·人工智能·chrome·python·算法·语言模型·自然语言处理
Είναι η κοπέλα14 小时前
PyTorch 模型导出与部署实战:ONNX + onnxruntime(可直接落地)
人工智能·pytorch·python
NutShell Wang14 小时前
Mojo 1.0 实战:把 Python 热路径原地加速到 C++ 级(四层渐进式迁移)
python·mojo·vibe coding
运维行者_14 小时前
预测性云监控怎么做?AI驱动的7大核心能力与落地路径
服务器·开发语言·网络·数据库·人工智能·python·php
呆萌很14 小时前
PyTorch CosineAnnealingLR的T_max和eta_min参数设置
人工智能·pytorch·python
aichitang202414 小时前
快乐泛函每一天!内积空间
c++·python·数学·算法·机器学习·ai·泛函分析