pip install flask-restful
使用
from flask import Flask from flask_restful import Api,Resource app = Flask(__name__) api = Api(app)#这里可以传Flask对象或者蓝图对象 class Helloworld(Resource): def post(self): return {'msg':"hello post world"} def get(self): return {'msg':'hello get world'} api.add_resource(Helloworld,'/',endpoint='hello')#参数:视图类名 路由地址 endpoint 别名 if __name__ == '__main__': app.run()
使用method_decorators
添加装饰器
- 为类视图中的所有方法添加装饰器
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_decorators = [decorator1, decorator2]#为所有请求方法加装饰器 排后面的装饰器套在越外层 method_decorators = {#为视图中不同方法加不同的装饰器 'get': [decorator1, decorator2], 'post': [decorator1] } def get(self): return {'msg': 'get view'} def post(self): return {'msg': 'post view'}
请求处理
关于请求处理
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
对象 -
向
RequestParser
对象中添加需要检验或转换的参数声明 -
使用
parse_args()
方法启动检验处理 -
检验之后从检验结果中获取参数时可按照字典操作或对象属性操作
args.rate 或 args['rate']
参数说明
1 required
描述请求是否一定要携带对应参数,替换为False
-
真正的强制要求携带
若未携带,则校准失败,向客户端返回错误信息,状态码400
-
错误不强制要求携带
若不强制携带,在客户端请求未携带参数时,收回估计无
class DemoResource(Resource): def get(self): rp = RequestParser() rp.add_argument('a', required=False) args = rp.parse_args() return {'msg': 'data={}'.format(args.a)}
2 help
参数检验错误时返回的错误描述信息
rp.add_argument('a', required=True, help='missing a param')
3 action
描述对于请求参数中出现多个同名参数时的处理方式
action='store'
保留出现的第一个,默认action='append'
以列表追加保存所有同名参数的值
rp.add_argument('a', required=True, help='missing a param', action='append')
4 type
描述参数应该匹配的类型,可以使用python的标准数据类型string,int,也可以使用Flask-RESTful提供的检验方法,还可以自己定义
-
标准类型
rp.add_argument('a', type=int, required=True, help='missing a param', action='append')
-
Flask-RESTful提供
检验类型方法在
flask_restful.inputs
模块中-
url
-
regex(指定正则表达式)
from flask_restful import inputs rp.add_argument('a', type=inputs.regex(r'^d{2}&'))
-
natural
自然数0、1、2、3 ... -
positive
正整数1、2、3 ... -
int_range(low ,high)
整个范围rp.add_argument('a', type=inputs.int_range(1, 10))
-
boolean
-
-
自定义
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)
5声明参数位置
描述参数应该在请求数据中出现的位置
# Look only in the POST body parser.add_argument('name', type=int, location='form') # Look only in the querystring parser.add_argument('PageSize', type=int, location='args') # From the request headers parser.add_argument('User-Agent', location='headers') # From http cookies parser.add_argument('session_id', location='cookies') # From json parser.add_argument('user_id', location='json') # From file uploads parser.add_argument('picture', location='files')
也可规范多个位置
parser.add_argument('text', location=['headers', 'json'])
响应(序列化数据)
from flask import Flask from flask_restful import reqparse, Api, Resource, marshal, fields app = Flask(__name__) api = Api(app) class User(object):#生成对象的类 def __init__(self,name,age,id): self.name = name self.age = age self.id = id resoure_fields = {#检验的字段 'age':fields.Integer, 'name':fields.String } # /demo?a=1 class Demo(Resource): def get(self): user = User('xujin',12,1)#生成对象 return marshal(user,resoure_fields,)#返回对象序列化之后的数据 api.add_resource(Demo,'/demo') if __name__ == '__main__': app.run()