1、安装
pip install falsk-restful
2、第一个flask-restful程序
from flask import Flask
#1、导入flask-restful工具类
from flask_restful import Api,Resource
app = Flask("__name__")
#2、实例化Api对象
api = Api(app)
@app.route("/index")
def index():
return 'hello world'
#3、定义视图类,必须继承自Resource
class index_resourse(Resource):
def get(self):
return 'Hello'
#4、添加路由
api.add_resource(index_resourse,'/') #第一个参数是端点名字,第二个路由
if __name__ == "__main__":
app.run(debug=True)
3、蓝图Blueprint 和flask-restful
from flask import Flask,Blueprint
#1、导入flask-restful工具类
from flask_restful import Api,Resource
app = Flask(__name__)
#2、实例化Api对象
bp = Blueprint('bp',__name__) #实例化蓝图对象
api = Api(bp) # 将蓝图添加到Api中
#3、定义视图类,必须继承自Resource
class index_resourse(Resource):
def get(self):
return {"get":'hello1'}
def post(self):
return {"post":'hello2'}
#4、添加路由
api.add_resource(index_resourse,'/') #第一个参数是端点名字,第二个路由
app.register_blueprint(bp)
if __name__ == "__main__":
print(app.url_map)
'''
Map([ bp.index_resourse>, 蓝图名称和端点名称
' (OPTIONS, GET, HEAD) -> static>])
'''
app.run(debug=True)
4、装饰器
from flask import Flask
from flask_restful import Resource,Api
app = Flask(__name__)
api = Api(app)
#添加装饰器
def decorator1(fun):
def inner(*arg,**kwargs):
print("decorator1 is run")
return fun(*arg,**kwargs)
return inner
def decorator2(fun):
def inner(*arg,**kwargs):
print("decorator2 is run")
return fun(*arg,**kwargs)
return inner
class resourse(Resource):
''' 以下分配装饰器比较常用
method_decorators = [decorator1,decorator2]
或者
method_decorators = {
'get':[decorator1],
'post':[decorator2]
}
'''
@decorator2 #适合于少量的方法需要添加装饰器
def get(self):
return {"get": 'hello1'}
@decorator1
def post(self):
return {"post": 'hello2'}
api.add_resource(resourse,'/')
if __name__=='__main__':
app.run(debug=True)
5、请求处理
from flask import Flask
from flask_restful import Resource,Api,reqparse,inputs
app = Flask(__name__)
api = Api(app)
class resourse(Resource):
def get(self):
req = reqparse.RequestParser() #实例化校验对象类
# req.add_argument('a',type='方法 或 inputs.regex(r"正则表达") 或指定类型str int 等 等',required=True,help='miss a')
req.add_argument('tysay',type=str,required=False,help='miss tysay')
# parse_args解析参数
args = req.parse_args()
print(args)
return {"get": 'hello'}
api.add_resource(resourse,'/')
if __name__=='__main__':
app.run(debug=True)
'''
需求:统一数据格式
默认情况下:{'get':'hello world'}
目标情况下:{'message':'ok','data':{'get':'hello world'}}
'''
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)