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)

执行结果:

相关推荐
Eward-an9 分钟前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
李昊哲小课14 分钟前
Python itertools模块详细教程
数据结构·python·散列表
小猪弟36 分钟前
【app逆向】某壳逆向的wll-kgsa参数,signature参数
python·逆向·wll-kgsa·signature·
对方正在长头发2251 小时前
写了个 Windows 端口映射管理工具,再也不用敲命令了
python
tang777891 小时前
哪些行业用动态代理ip?哪些行业用静态代理IP?怎样区分动态ip和静态ip?(互联网人必码·实用长文)
大数据·网络·爬虫·python·网络协议·tcp/ip·智能路由器
龙泉寺天下行走1 小时前
LangChain Skills框架核心解析
python·langchain·aigc
echome8881 小时前
Python 装饰器详解:从入门到精通的实用指南
开发语言·python
tang777891 小时前
爬虫代理IP池到底有啥用?
网络·爬虫·python·网络协议·tcp/ip·ip
sg_knight1 小时前
设计模式实战:享元模式(Flyweight)
python·设计模式·享元模式·flyweight