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)

执行结果:

相关推荐
坐吃山猪1 小时前
Python进度条
linux·服务器·python
l1t2 小时前
四种python工具包用SQL查询csv和parquet文件的方法比较
大数据·python·sql
清水白石0082 小时前
Python 并发三剑客:多线程、多进程与协程的实战抉择
java·服务器·python
2301_793804692 小时前
更优雅的测试:Pytest框架入门
jvm·数据库·python
dinl_vin2 小时前
python:常用的基础工具包
开发语言·python
wefly20172 小时前
无需安装、开箱即用!m3u8live.cn 在线 HLS 播放器,调试直播流效率翻倍
前端·后端·python·前端开发工具·后端开发工具
2301_815482933 小时前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
将心ONE3 小时前
melo tts安装使用
python
宸翰4 小时前
Python学习:年轻人的第一个入门Python项目(FastAPI版)
后端·python
AsDuang4 小时前
Python 3.12 MagicMethods - 55 - __irshift__
开发语言·python