why learn it?
Flask_RESTful —>快速构建REST API的Flask扩展
安装
pip install flask_restful
案列:
from flask import Flask
from flask_restful import Resouce, Api
app = Flask(__name__)
api = Api(app)
class DemoResource(Resource):
def get(self):
return {'hello': 'world'}
def post(self):
return {'msg': 'post hello world'}
api.add_resource(DemoResource, '/')
对比原生flask:
1. 路由
app.add_resource(DemoResource, '/demo', endpoint = ”demo“)
2. 蓝图中使用
from flask import Flask,Blueprint
from flask_restful import Api, Resource
app = Flask(__name__)
user_bp = Blueprint('user',__name__)
user_api = Api(user_bp)
class UserProfileResource(Resource):
def get(self):
return {'msg':'get user profile'}
user_api.add_resource(UserProfileResource,'/user/profile', endpoint='userprofile')
app.register_blueprint(user_bp)
对比app中 使用restful和蓝图
3. 装饰器
添加装饰器:method_decorators
class DemoResource(Resource)
method_decorators = [decorator1, decorator2]
def ...
method_decorators = {
'get': [decorator1, decorator2],
'post': [decorator1]
}
flask_restful ----> RequestParser–>(检验、转换请求数据。)
步骤:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Rate cannot be converted', location='args')
parser.add_argument('name')
args = parser.parse_args()
参数说明
第三步,向requestparser对象中添加需要转化、检验的请求数据。
rp.add_argument('a',required=True, help='missing a param')
rp.add_argument('a', type = int, required=True, help='miss a param', action='append')
(2)
from flask_restful import inputs
rp.add_argument('a',type = inputs.regex(r'^\d{2}&'))
(5)
rp.add_argument('a', type = inputs.int_range(1, 10))
def mobile(mobile_str):
"""
检验手机号格式
:param mobile_str: str 被检验字符串
:return: mobile_str
"""
if re.match(r'^1[3-9]\d{9}$', mobile_str):
return mobile_str
else:
raise ValueError('{} is not a valid mobile'.format(mobile_str))
rp.add_argument('a', type=mobile)
ofcurse! ------可指明多个位置
parser.add_argument('text',location=['headers','json'])
Flask-RESTful提供了marshal---->将数据序列化为特定格式的字典数据---->作为视图的返回值。
任何对象--------->字典
from flask_restful import fields,marshal,marshal_with,Resource
resource_fields = {
'name':fields.String,
'age':fields.Integer
}
class DemoResource0(Resource):
@marshal_with(resource_fields,envelope='data')
def get(self):
user = User.object.get(id=1)
return user
class DemoResource1(Resource):
def get(self):
user = User.object.get(id=1)
# 除了指明字段和envelope之外,还需指明要处理的对象是谁。
return marshal(user, resource_fields,envelope='data')
envelope: 信封--------->{‘data’:{‘user’:‘小王’,‘age’:18}}
需求:规定接口返回的json数据具有统一的格式
{"message": "描述信息", "data": {要返回的具体数据}}
representation<-----------------Flask-RESTful的Api对象------------>定制返回数据的呈现格式。
representation:相当于哟个钩子,允许你挂个函数——指定返回数据格式
@api.representation('application/json')
def func()
处理内容
...
在视图函数中得到得返回数据,并不立刻直接返回给客户端,而是先经过被representation装饰得函数之后再返回。
method:
修改flask_restful.representations.json代码:
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
# 此处为自己添加***************
if 'message' not in data:
data = {
'message': 'OK',
'data': data
}
# **************************
settings = current_app.config.get('RESTFUL_JSON', {})
# If we're in debug mode, and the indent is not set, we set it to a
# reasonable value here. Note that this won't override any existing value
# that was set. We also set the "sort_keys" value.
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', not PY3)
# always end the json dumps with a new line
# see https://github.com/mitsuhiko/flask/pull/1262
dumped = dumps(data, **settings) + "\n"
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp