基本使用扩展介绍环境安装pip install flask-restful文档构建RESTAPI #### 代码示例 [Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
# 创建API对象
api = Api(app)
# 定义类视图 继承Resource
class DemoResource(Resource):
def get(self):
return {'foo':'get'}
def post(self):
return {'foo':'post'}
# 添加类视图 函数标记默认为类名小写
api.add_resource(DemoResource, '/', endpoint='demo')
if __name__ == '__main__':
print(app.url_map)
app.run(debug=True) 类视图的优点 一个类视图里面可以处理不同的HTTP请求方法 帮助构建JSON返回数据
类视图设置装饰器代码示例[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
def decorator1(func):
def wrapper(*args, **kwargs):
print('decorator1')
return func(*args, **kwargs)
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print('decorator2')
return func(*args, **kwargs)
return wrapper
class DemoResource(Resource):
# method ① 列表形式 设置method_decorators类属性
method_decorators = [decorator1, decorator2]
# method_decorators = {
# 'get': [decorator1],
# 'post': [decorator2]
# }
def get(self):
return {'foo': 'get'}
def post(self):
return {'foo': 'post'}
api.add_resource(DemoResource, '/', endpoint='demo')
if __name__ == '__main__':
app.run(debug=True)
蓝图和类视图蓝图和类视图可以配合使用,步骤如下: 创建蓝图对象 每个蓝图分别创建组件对象 组件对象添加类视图 应用注册蓝图
代码示例[Python] 纯文本查看 复制代码 # user/views.py
from flask_restful import Resource
class DemoResource(Resource):
def get(self):
return {'foo': 'get'}
def post(self):
return {'foo': 'post'}
user包的初始化文件 __init__.py中
创建蓝图对象 通过蓝图对象创建对应的组件对象 组件对象添加类视图
[Python] 纯文本查看 复制代码 from flask import Blueprint
from flask_restful import Api
from .views import DemoResource
# 创建蓝图对象
user_blue = Blueprint('user', __name__)
# 通过蓝图对象创建对应的组件对象
user_api = Api(user_blue)
# 组件对象添加类视图
user_api.add_resource(DemoResource, '/')
[Python] 纯文本查看 复制代码 # main.py
from flask import Flask
from user import user_blue
app = Flask(__name__)
app.register_blueprint(user_blue)
if __name__ == '__main__':
print(app.url_map)
app.run(debug=True)
请求请求解析代码示例
[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Resource, Api
from flask_restful.reqparse import RequestParser
app = Flask(__name__)
api = Api(app)
class DemoResource(Resource):
def get(self):
# ① 创建解析器
parser = RequestParser()
# ② 添加参数规则
parser.add_argument('name')
parser.add_argument('age')
# ③ 执行解析
args = parser.parse_args()
# ④ 获取参数
print(args.name)
print(args.age)
return {'foo': 'get'}
api.add_resource(DemoResource, '/', endpoint='demo')
if __name__ == '__main__':
print(app.url_map)
app.run(debug=True)
常用参数参数 说明 取值
default给参数设置默认值,如果不传递该参数就会使用默认值True/False
required是否必须传递,默认False,如果设置为True,不传递会返回400True/False
location设置参数提取的位置args/form/json/files/headers/
type设置参数的转换类型(类型转换 & 格式校验)函数引用,int/内置类型/自定义函数代码示例[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Resource, Api
from flask_restful.reqparse import RequestParser
app = Flask(__name__)
api = Api(app)
class DemoResource(Resource):
def post(self):
parser = RequestParser()
parser.add_argument('name', required=True, location='json')
parser.add_argument('age', default=18)
args = parser.parse_args()
print(args.name)
print(args.age)
return {'foo': 'get'}
api.add_resource(DemoResource, '/', endpoint='demo')
if __name__ == '__main__':
app.run(debug=True)
[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Resource, Api
from flask_restful.inputs import boolean, date, datetime_from_iso8601, int_range, regex
from flask_restful.reqparse import RequestParser
app = Flask(__name__)
api = Api(app)
def custom_func(value):
if int(value) < 18:
raise ValueError('没有满18岁')
else:
return value
class DemoResource(Resource):
def post(self):
parser = RequestParser()
parser.add_argument('name', required=True, location='json')
# parser.add_argument('age', default=18, type=int)
# parser.add_argument('age', default=18, type=boolean)
# parser.add_argument('age', default=18, type=date) # xx-xx-xx
# parser.add_argument('age', default=18, type=datetime_from_iso8601)
# parser.add_argument('age', default=18, type=int_range(1, 10))
# parser.add_argument('age', default=18, type=regex(r'1[3-9]\d{9}'))
parser.add_argument('age', type=custom_func)
args = parser.parse_args()
print(args.name)
print(args.age)
print(type(args.age))
return {'foo': 'get'}
api.add_resource(DemoResource, '/', endpoint='demo')
if __name__ == '__main__':
app.run(debug=True)
响应序列化序列化类型 说明
String可转换 字符串类型属性
Integer可转换 整数类型属性
Float可转换 浮点数类型属性
List可转换 列表类型属性,要求列表中元素类型唯一
Nested可转换 字典类型属性代码示例
[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Resource, Api, marshal, fields
app = Flask(__name__)
api = Api(app)
class User:
def __init__(self):
self.name = 'itcast'
self.age = 20
self.height = 1.8
self.scores = [100, 99]
self.info = {
'gender': True
}
serializer = {
'username': fields.String(attribute='name'),
'age': fields.Integer(default=10),
'height': fields.Float,
'scores': fields.List(fields.Integer),
'info': fields.Nested({'gender': fields.Boolean})
}
class DemoResource(Resource):
def get(self):
user = User()
return marshal(user, serializer, envelope='data')
api.add_resource(DemoResource, '/')
if __name__ == '__main__':
app.run(debug=True)
[Python] 纯文本查看 复制代码 from flask import Flask
from flask_restful import Resource, Api, marshal, fields, marshal_with
app = Flask(__name__)
api = Api(app)
class User:
def __init__(self):
self.name = 'itcast'
self.age = 20
self.height = 1.8
self.scores = [100, 99]
self.info = {
'gender': True
}
serializer = {
'username': fields.String(attribute='name'),
'age': fields.Integer(default=10),
'height': fields.Float,
'scores': fields.List(fields.Integer),
'info': fields.Nested({'gender': fields.Boolean})
}
class DemoResource(Resource):
method_decorators = {
'get': [marshal_with(serializer, envelope='data')]
}
def get(self):
user = User()
return user
api.add_resource(DemoResource, '/')
if __name__ == '__main__':
app.run(debug=True)
|