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)

执行结果:

相关推荐
第二个人6 小时前
Python Web开发:从Flask到FastAPI,我经历了什么
前端·python·flask
這花開嗎1 天前
2026年TTS文字转语音API哪家强?批量自动化配音成本与技术实测
python·flask·自动化
Albart5751 天前
2026年Python入门路线图:从零到实战的30天逐日详解(三)
学习·flask·#python30 天入门·python 实战教程·pytest 单元测试·python 虚拟环境·logging 日志
weixin_446260852 天前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
weixin_BYSJ19872 天前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
暮暮祈安3 天前
Celery 新手入门指南
java·数据库·python·flask·httpx
小大宇3 天前
python flask框架 SSE流式返回、跨域、报错
开发语言·python·flask
编码者卢布3 天前
【Azure Policy】Policy修正任务为Azure资源添加诊断日志报错问题的调查
microsoft·flask·azure
编码者卢布5 天前
【Azure APIM】APIM的诊断日志与Application Insights的日志是否可以串联为一个端到端的日志链路呢?
python·flask·azure
weixin_BYSJ19876 天前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php