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)

执行结果:

相关推荐
我的xiaodoujiao21 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest
安冬的码畜日常21 小时前
【JUnit实战3_29】第十八章:REST API 接口测试(上)——RESTful 风格的后端 API 的搭建
测试工具·单元测试·restful·rest api·junit 5
开心-开心急了21 小时前
关于Flutter与Qt for python 的一些技术、开源、商用等问题
开发语言·python·qt·flutter
@小码农21 小时前
2025年北京海淀区中小学生信息学竞赛第一赛段试题(附答案)
人工智能·python·算法·蓝桥杯
schinber1 天前
使用pycharm自带debug模式运行flask时报错
ide·pycharm·flask
Q_Q19632884751 天前
python+django/flask基于机器学习的就业岗位推荐系统
spring boot·python·django·flask·node.js·php
ArabySide1 天前
【Spring Boot】REST与RESTful详解,基于Spring Boot的RESTful API实现
spring boot·后端·restful
AI科技星1 天前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine1 天前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
ithicker1 天前
Pycharm+Deepseek结合使用Continue插件无法返回中文产生乱码
ide·python·pycharm