Flask restful Api基于蓝图,实现解耦
安装flask-restful from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) //封装app class HelloWorld(Resource): def get(self,todo_id): return {"name":"alex"}
def put(self,todo_id):
pass
api.add_resource(HelloWorld,'/<string:todo_id>') //路由,资源和url建立映射关系
一种资源只能添加一次,#url匹配到http://127.0.0.1:5000/todo.?
if __name__ == "__main__": app.run(debug=True,host="0.0.0.0")
#基于蓝图实现,目录结构如下
#run.py from flask import Flask from views import user_bp app = Flask(__name__) # app.register_blueprint(user_bp.user_bp) # # app.register_blueprint(order_bp) # if __name__ == "__main__": app.run()
#user_bp.py from flask import Blueprint from flask_restplus import Api,Resource, fields #创建蓝图对象,解耦不同业务的接口 user_bp = Blueprint("user",__name__,url_prefix="/user") #user参数,用于url_for翻转使用,url_prefix用于区分不同的蓝图路由 # print(url_for("user.printf")) 没有endpoint,默认是函数名 api = Api(user_bp) # 数据校验格式 tu_info = api.model("tuInfo",{ "tuName": fields.String(required=True,description="测试项名称", enum=["Demo"]), "uuid": fields.Raw(required=True,description="自定义对象") }) cloud_ate_base = api.model("cloudAteBase",{ "version": fields.String(required=True, description="版本信息", enum=["v1.0.0.0"]), "tuinfo": fields.Nested(tu_info,required=True,description="测试项信息") }) comrst = api.model("Commonresult",{ "result": fields.Boolean(required=True, description="返回值=[True, False]"), "value": fields.Raw(required=True,description="返回结果=[string,list,dict]"), "info": fields.Raw(required=True, description="失败错误原因") }) ns = api.namespace("Version", description="版本") #使用API进行restful风格 @api.route("/index","/nomal") #支持多个路由指向同一资源 class Demo(Resource): #数据校验 # @ns.expect(cloud_ate_base) @ns.marshal_with(comrst) def get(self): "逻辑处理" return {"result": True, "value": "测试结果", "info": "todo "}#返回结果进行marshal_with处理(字段类型一直)
Take a small step every day