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)

执行结果:

相关推荐
九亿AI算法优化工作室&20 分钟前
GWO优化SVM回归预测matlab
人工智能·python·matlab·数据挖掘·回归
Zda天天爱打卡28 分钟前
【Numpy核心编程攻略:Python数据处理、分析详解与科学计算】2.19 线性代数核武器:BLAS/LAPACK深度集成
python·线性代数·numpy
golitter.33 分钟前
python的pre-commit库的使用
开发语言·python
Bran_Liu1 小时前
【LeetCode 刷题】贪心算法(1)-基础
python·算法·leetcode·贪心算法
码界筑梦坊1 小时前
基于Flask的商城应用系统的设计与实现
后端·python·flask·毕业设计
查士丁尼·绵1 小时前
笔试-业务逻辑5
python
Ronin-Lotus2 小时前
深度学习篇---二维码&预训练模型
人工智能·pytorch·python·深度学习·tensorflow·paddlepaddle·二维码
Cacciatore->2 小时前
TensorFlow 与 PyTorch 的直观区别
人工智能·pytorch·python·深度学习·机器学习·tensorflow
DaisyMosuki2 小时前
Selenium记录RPA初阶 - 基本输入元件
python·selenium·测试工具
Giser@lin2 小时前
Python安居客二手小区数据爬取(2025年)
开发语言·redis·python