tips:
在项目开发中,通常采用工程模式来创建app,如果注册接口写在工厂函数中,不仅不好管理,而且代码也看起来很臃肿。并且项目中会有很多模块,每个模块又有不同的功能,由此分割出来的接口也非常多。所有需要有统一的地方来管理接口及相关模块。
编写蓝图(user.py
)
from flask import Blueprintbp = Blueprint("test", __name__, url_prefix='/')@bp.route('/testBP', methods=["GET"])def test_bp(): return "蓝图测试"
编写自定义MethodView(auth.py
)
from flask.views import MethodViewclass AuthMethodView(MethodView): # 指定需要启用的请求方法 __methods__ = ["GET", "POST", "PUT"] def get(self): return "测试自定义MethodView" def post(self): return "测试自定义MethodView" def put(self): return "测试自定义MethodView" def delete(self): return "测试自定义MethodView"
统一管理蓝图和自定义MethodView(router.py
)
from user import bp as user_bpfrom auth import AuthMethodViewrouter = [ user_bp, # 用户蓝图接口 AuthMethodView, # 权限自定义MethodView]
统一注册蓝图和自定义MethodView(app.py
)
from flask import Flask, Blueprintfrom router import routerdef create_app(): """ 工厂模式创建APP """ app = Flask(__name__) # 注册接口 register_api(app, router) return appdef register_api(app, routers): """ 注册蓝图和自定义MethodView """ for router in routers: if isinstance(router, Blueprint): app.register_blueprint(router) else: try: endpoint = router.__name__ view_func = router.as_view(endpoint) # url默认为类名小写 url = '/{}/'.format(router.__name__.lower()) if 'GET' in router.__methods__: app.add_url_rule(url, defaults={'key': None}, view_func=view_func, methods=['GET', ]) app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['GET', ]) if 'POST' in router.__methods__: app.add_url_rule(url, view_func=view_func, methods=['POST', ]) if 'PUT' in router.__methods__: app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['PUT', ]) if 'DELETE' in router.__methods__: app.add_url_rule('{}<string:key>'.format(url), view_func=view_func, methods=['DELETE', ]) except Exception as e: raise ValueError(e)if __name__ == '__main__': app = create_app() app.run()
测试,启动app
浏览器访问http://127.0.0.1:5000/testBP
,页面返回蓝图测试
浏览器访问http://127.0.0.1:5000/authmethodview/
,页面返回测试自定义MethodView
联系客服