Flask高级_restful之规范返回值
一.规范返回值的方法
在请求方法中,返回自定义对象的时候,flask_restful会自动的读 取对象模型上的所有属性。
组装成一个符合标准化参数的json格式字符串返回给客户端。
二.参数设置
三.类型设置
返回的值里有json或者列表数据,这时可以通过以字段来实现
四.实例
规范设置与参数:
#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())