关于Flask高级_restful之规范返回值的方法

Flask高级_restful之规范返回值

一.规范返回值的方法

  1. 导入 flask_restful.marshal_with 装饰器
  2. 定义一个字典变量来指定需要返回的标准化字段,以及该字段的数据类型
在请求方法中,返回自定义对象的时候,flask_restful会自动的读 取对象模型上的所有属性。
组装成一个符合标准化参数的json格式字符串返回给客户端。

二.参数设置

  • 设置重命名属性
    fields.String(attribute='username')
    
  • 设置默认值
    fields.String(default='qf')
    

三.类型设置

返回的值里有json或者列表数据,这时可以通过以字段来实现
  • fields.List 放置一个列表
  • fields.Nested放置一个字典

四.实例

规范设置与参数:
#coding=utf-8

import code
from socket import MsgFlag
from flask import Flask
from flask_restful import Resource,Api,marshal_with,fields

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

class News:
    def __init__(self,code,msg,state) -> None:
        self.code = code
        self.msg = 'qwer'
        self.state = state
        self.content = msg
class jsonView(Resource):
    resource_fields = {
        # 对于使用News类对象
        # 如果不传code值,则默认为404;
        # 如果传了code值,则为code值;
        # 如果News中的code属性有code默认值,则为默认值,不是default中设置的值
        'code':fields.Integer(default=404),

        # 设置msg提取数据的字段为'data'段
        'msg':fields.String(attribute='content'),
        'state':fields.String
    }

    @marshal_with(resource_fields)
    def get(self):
        return {'msg':'qwer','content':'hhh'}

    @marshal_with(resource_fields)
    def post(self):
        return {'state':'app'}

    @marshal_with(resource_fields)
    def put(self):
        return News('404','hhh','app')

api.add_resource(jsonView,'/')

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

在这里插入图片描述
在这里插入图片描述

类型设置:
#coding=utf-8

from flask import Flask
from flask_restful import Api,Resource,marshal_with,fields

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

class User:
    def __init__(self,uname) -> None:
        self.uname = uname

    def __repr__(self) -> str:
        return f'<User uname:{self.uname}>'

class NewsType:
    def __init__(self,_type) -> None:
        self._type = _type

    def __repr__(self) -> str:
        return f'<User type:{self._type}>'

class News:
    def __init__(self,code,msg) -> None:
        self.code = code
        self.msg = msg
        self.user = None
        self._type = []

    def __repr__(self) -> str:
        return f'<News code:{self.code} msg:{self.msg}> user:{self.user} type:{self._type}'


def create_news():
    user = User('hh')
    _type1 = NewsType('IT')
    _type2 = NewsType('Python')
    news = News(200,'qf')
    news.user = user
    news._type.append(_type1)
    news._type.append(_type2)
    return news

class NewsView(Resource):
    resource_fields = {
        'code':fields.Integer,
        'msg':fields.String,
        'user':fields.Nested({
            'uname':fields.String
        }),
        '_type':fields.List(fields.Nested({
            '_type':fields.String
        }))
    }

    @marshal_with(resource_fields)
    def get(self):
        return create_news()

api.add_resource(NewsView,'/')

if __name__ == '__main__':
    app.run(debug=True)
    # print(create_news())

在这里插入图片描述

注:
如果觉得笔记有些问题,麻烦在百忙之中在评论中指正,或提出建议!另外,如果觉得这份笔记对你有所帮助,麻烦动动发财的小手手点一波赞!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值