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)

执行结果:

相关推荐
立心者01 小时前
Sdcb Chats .. 发布,彻底移除 Azure.AI.OpenAI 专用包
人工智能·flask·azure
昆曲之源_娄江河畔21 小时前
Python如何安装flask, pymssql
开发语言·python·flask·pymssql
韭菜炒鸡肝天1 天前
【App Service】在Azure环境中如何查看App Service实例当前的网络连接情况呢?
microsoft·flask·azure
看昭奚恤哭1 天前
ontainer App】Container App无法从Container Registries 拉取镜像 - 报错 Forbidden
后端·python·flask
米码收割机1 天前
【python】Flask 贵州省兴仁市藠头价格数据分析和可视化系统(源码+文档)【独一无二】
python·数据分析·flask
zhiSiBuYu05172 天前
Flask 模板渲染新手实战指南
后端·python·flask
zhiSiBuYu05172 天前
Flask 视图函数新手实战指南
后端·python·flask
m沐沐2 天前
【深度学习】模型部署全解析——从原理到Flask服务端实战
人工智能·后端·python·深度学习·opencv·flask
zhiSiBuYu05173 天前
Flask 路由新手入门与实战指南
后端·python·flask
zhiSiBuYu05173 天前
Flask 请求与响应新手实战指南
后端·python·flask