flask_restful规范返回值之参数设置

设置重命名属性和默认值
使用 attribute 配置这种映射 , 比如: fields.String(attribute='username')
使用 default 指定默认值,比如: fields.String(default='sxt')

复制代码
from flask import Flask,render_template
from flask_restful import Api,Resource,fields,marshal_with

app = Flask(__name__)
api =Api(app)

class News:
    def __init__(self,code,msg,info):
        self.code = code
        self.msg = msg
        self.info = info
        self.state= 1000

class NewsView(Resource):
    resouce_fileds = {
        # 通过参数default来设置默认值
        'code':fields.Integer(default=200),
        'msg':fields.String,
        # 通过参数attribute来设置提取数据的字段
        'content':fields.String(attribute='info'),
        # 优先级不如真实数据里面的高
        'state':fields.Integer(default=2000)
         }
    @marshal_with(resouce_fileds)
    def get(self):
        return News(200,'访问成功!','移动')
    
    @marshal_with(resouce_fileds)
    def post(self):
        return {'msg':'增加数据成功','info':'联通'}
    
    @marshal_with(resouce_fileds)
    def put(self):
        # 在返回对象时,会自动在对象中获取与约定好的字段,并获取分装成json
        news = News(404,'访问成功','移动')
        return news

api.add_resource(NewsView,'/news/')

if __name__=="__main__":
    app.run(debug=True)

执行结果:

相关推荐
Hooray112 天前
后端_Flask学习笔记
笔记·后端·python·学习·flask
速易达网络2 天前
Python全栈学习路径:从零基础到人工智能实战
python·flask
中文很快乐2 天前
从零到一:用 SpringBoot 打造 RESTful API 实战指南
java·spring boot·后端·restful
爱上妖精的尾巴3 天前
6-1WPS JS宏 new Set集合的创建
前端·后端·restful·wps·js宏·jsa
计算机学姐3 天前
基于Python的智能点餐系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
MUTA️3 天前
使用flask将服务器端的视频通过网页在本地查看
后端·python·flask
计算机学姐3 天前
基于Python的在线考试系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
爱上妖精的尾巴3 天前
5-39 WPS JS宏 综合实例应用-4(多条件筛选记录并排序)
java·后端·restful·wps·js宏·jsa
Q_Q5110082853 天前
python+springboot+django/flask基于深度学习的音乐推荐系统
spring boot·python·django·flask·node.js·php
Q_Q5110082853 天前
python+springboot+django/flask基于深度学习的淘宝用户购物可视化与行为预测系统
spring boot·python·django·flask·node.js·php