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)

执行结果:

相关推荐
阿幸软件杂货间6 分钟前
PPT转图片拼贴工具 v1.0
python·powerpoint
AIGC_北苏19 分钟前
DrissionPage爬虫包实战分享
爬虫·python·drissionpage
YBCarry_段松啓1 小时前
uv:下一代 Python 包管理器
人工智能·python
yorushika_1 小时前
python打卡训练营打卡记录day45
开发语言·python·深度学习·tensorboard
封奚泽优1 小时前
使用Python进行函数作画
开发语言·python
fc&&fl1 小时前
大模型面试题总结
人工智能·python
databook1 小时前
稀疏表示与字典学习:让数据“瘦身”的魔法
python·机器学习·scikit-learn
Sheeep2 小时前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
站大爷IP3 小时前
用Python打造办公效率神器:从数据到文档的全流程自动化实践
python
hongjianMa3 小时前
ModuleNotFoundError No module named ‘torch_geometric‘未找到
python