ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Blueprint和route的区别

Blueprint和route的区别 蓝图和路由的区别?main_bp.route和app.route本质都是给视图函数绑定 URL区别在于app.route直接注册到 Flask 应用main_bp.route先注册到蓝图蓝图再通过app.register_blueprint()注册到应用。代码对比方式一直接用app.routefromflaskimportFlask,render_template appFlask(__name__)app.route(/)defindex():returnrender_template(index.html)app.route(/login)deflogin():return登录页app.route(/register)defregister():return注册页if__name____main__:app.run()方式二用蓝图main_bp.route# app/main/__init__.pyfromflaskimportBlueprint main_bpBlueprint(main,__name__)fromapp.mainimportroutes# 导入路由避免循环导入# app/main/routes.pyfromflaskimportrender_templatefromapp.mainimportmain_bpmain_bp.route(/)defindex():returnrender_template(index.html)# app/auth/routes.pyfromflaskimportBlueprint auth_bpBlueprint(auth,__name__)auth_bp.route(/login)deflogin():return登录页auth_bp.route(/register)defregister():return注册页# app/__init__.pyfromflaskimportFlaskfromapp.mainimportmain_bpfromapp.authimportauth_bpdefcreate_app():appFlask(__name__)app.register_blueprint(main_bp)# /app.register_blueprint(auth_bp,url_prefix/auth)# /auth/login, /auth/registerreturnapp主要区别维度app.routemain_bp.route注册对象直接注册到app先注册到蓝图再由app注册URL 前缀每个路由手动写注册时可统一加url_prefix代码组织适合小项目路由容易堆在一起适合按模块拆分如 main、auth、apiurl_forurl_for(index)url_for(main.index)复用性不可复用同一个蓝图可注册到多个应用或不同前缀独立资源共用templates/、static/蓝图可配置自己的模板和静态文件目录企业里哪个用得多中小项目、练习项目、原型项目app.route更常见因为简单直接文件少不用一开始就拆模块。正式项目、多人协作项目、中大型项目蓝图用得更多。实际工作中Flask 项目通常会按功能拆成main、auth、api、admin等蓝图再配合create_app工厂模式。简单判断只有一个文件、几个路由 → 用app.route就行。有登录、后台、API、用户中心等多个模块 → 用蓝图更合适。准备做测试、多环境配置、多人开发 → 蓝图 create_app是更常见的工程化写法。
返回列表