Flask blueprint蓝图按功能模块化架构实例
使用flask作为开发框架,一定要按功能模块化,否则到了后面项目越大,开发速度就越慢。
1、Flask模块化结构规划[root@yang-218yangyun]#tree.├──asset#资产功能目录│├──__init__.py│├──models.py#资产数据库结构文件│└──views.py#资产视图文件├──user#用户功能目录│├──__init__.py│├──models.py#用户数据库结构文件│└──views.py#用户视图配置文件├──config.py#公共配置文件├──requirements.txt#需要的安装包├──run.py#主运行文件├──static#静态文件目录,css,js,p_w_picpath等└──templates#静态页面存放目录├──asset#asset功能模块页面存放目录│└──index.html├──index.html#首页└──user└──index.html2、run.py主运行文件配置
[root@yang-218 yangyun]# cat run.py
fromflaskimportFlaskfromassetimportassetfromuserimportuserapple=Flask(__name__,template_folder='templates',#指定模板路径,可以是相对路径,也可以是绝对路径。static_folder='static',#指定静态文件前缀,默认静态文件路径同前缀#static_url_path='/opt/auras/static',#指定静态文件存放路径。)apple.register_blueprint(asset,url_prefix='/asset')#注册asset蓝图,并指定前缀。apple.register_blueprint(user)#注册user蓝图,没有指定前缀。if__name__=='__main__':apple.run(host='0.0.0.0',port=8000,debug=True)#运行flaskhttp程序,host指定监听IP,port指定监听端口,调试时需要开启debug模式。
其它的功能模块配置相似
1) __init__.py文件配置
[root@yang-218 asset]# cat __init__.py
fromflaskimportBlueprintasset=Blueprint('asset',__name__,#template_folder='/opt/auras/templates/',#指定模板路径#static_folder='/opt/auras/flask_bootstrap/static/',#指定静态文件路径)importviews
2) views.py文件配置
[root@yang-218 asset]# cat views.py
fromflaskimportrender_templatefromassetimportasset@asset.route('/')#指定路由为/,因为run.py中指定了前缀,浏览器访问时,路径为http://IP/asset/defindex():print'__name__',__name__returnrender_template('asset/index.html')#返回index.html模板,路径默认在templates下
3)前端页面配置
[root@yang-218yangyun]#echo'Thisisassetindexpage...'>templates/asset/index.html
4、user功能模块配置此处配置和上述asset的配置一致
1) __init__.py配置
[root@yang-218 yangyun]# cat user/__init__.py
fromflaskimportBlueprintuser=Blueprint('user',__name__,)importviews
2) views.py配置
[root@yang-218 yangyun]# cat user/views.py
fromflaskimportrender_templatefromuserimportuser@user.route('/')defindex():print'__name__',__name__returnrender_template('user/index.html')
3) 静态页面配置
echo'ThisisUserpage....'>templates/user/index.html
5、requirements.txt文件配置主要作用是记录需要的依赖包,新环境部署时安装如下依赖包即可,pip安装命令: pip install -r requirements.txt
[root@yang-218yangyun]#catrequirements.txtFlask==0.10.1Flask-Bootstrap==3.3.5.6Flask-Login==0.2.11Flask-SQLAlchemy==2.0Flask-WTF==0.12
6、浏览器访问测试后端运行程序
[root@yang-218yangyun]#pythonrun.py*Runningonhttp://0.0.0.0:8000/(PressCTRL+Ctoquit)*Restartingwithstat
前端访问asset页面
前端访问user页面
为什么出现404?因为在run.py里没有指定前缀,所以url里不需要加user。
以上
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。