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)

执行结果:

相关推荐
Java面试题总结33 分钟前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
纸小铭43 分钟前
[MAF预定义ChatClient中间件-01]LoggingChatClient——在调用LLM前后输出日志
python·中间件·flask
aiqianji1 小时前
有哪些支持长文的AI生成短篇小说软件?
人工智能·python
狗都不学爬虫_1 小时前
AI逆向 - 某定制瑞树6纯算(ck-header-params后缀)
爬虫·python·网络爬虫
三十岁老牛再出发1 小时前
07.08.&07.09.每日总结
c语言·python
齐 飞1 小时前
Python常用语法总结
python
齐 飞1 小时前
LangGraph快速入门-03节点与边
python·langchain
_Jimmy_2 小时前
Python 多线程使用和场景
python
liulilittle2 小时前
Exhaustive drift-fix simulation V2 — KCC on shared-bottleneck wired path.
开发语言·网络·python·tcp/ip·计算机网络·信息与通信·通信
梦想的初衷~2 小时前
【完整教程】基于Python的无人机多光谱-点云融合生态三维建模:从Metashape重建到碳储量/生物量/LULC预测
python·无人机·三维重建·多光谱·无人机遥感·碳储量·生态建模