Python全系列 教程
3567个小节阅读:5929.6k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
大型的互联网项目中,返回的数据格式,有时是比较复杂的结构。
如:豆瓣电影
https://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=&start=20&limit=20
返回的值里有json或者列表数据,这时可以通过以字段来实现
xxxxxxxxxx
from flask import Flask
from flask_restful import Api,Resource,fields,marshal_with
app = Flask(__name__)
api = Api(app)
class User:
def __init__(self,uname):
self.uname = uname
def __repr__(self):
return f'<User uname:{self.uname}>'
class NewsType:
def __init__(self,_type):
self._type = _type
def __repr__(self):
return f'<User type:{self._type}>'
class News:
def __init__(self,code,msg):
self.code = code
self.msg = msg
self.user = None
self._type = []
def __repr__(self):
return f'<News code:{self.code} msg:{self.msg} user:{self.user} type:{self._type}>'
def create_data():
user = User('尚学堂')
_type1 = NewsType('IT')
_type2 = NewsType('Python')
news = News(200,'Python又双叕更新了!')
news.user = user
news._type.append(_type1)
news._type.append(_type2)
return news
class NewsView(Resource):
resouce_fields ={
'code':fields.Integer,
'msg':fields.String,
'user':fields.Nested({
'uname':fields.String
}),
'_type':fields.List(fields.Nested({
'_type':fields.String
}))
}
@marshal_with(resouce_fields)
def get(self):
news = create_data()
return news
api.add_resource(NewsView,'/news/')
if __name__ == '__main__':
app.run(debug=True)
# print(create_data())
实时学习反馈
1. 在Flask-RESTFul中,对于规范返回值类型设置说法错误的?
A 可以通过在flask_restful.fields
中的类型设置数据类型
B 可以通过在flask_restful.fields.List
设置返回类型为列表
C 可以通过在flask_restful.fields.Nested
设置返回类型为字典
D 可以通过在flask_restful.fields.Object
设置返回类型为对象
答案
1=>D