flask之Blueprint蓝图

flask_Blueprint.py

 1 '''
 2 flask中的Blueprint蓝图:
 3     (1)新建模块,例如Bp1.py,Bp2.py,在模块中创建蓝图实例
 4     (2)通过app.register_blueprint()对蓝图对象进行注册
 5     (3)如果在蓝图中设置了参数url_prefix就必须在请求的端口后路径前加上
 6 '''
 7 
 8 from flask import Flask, Blueprint, render_template
 9 
10 app = Flask(__name__)
11 app.config['DEBUG'] = True
12 
13 # 导入蓝图,通过app.register_blueprint()对蓝图对象进行注册
14 from Bp1 import Bp1
15 from Bp2 import Bp2
16 
17 app.register_blueprint(Bp1)
18 app.register_blueprint(Bp2)
19 
20 
21 @app.route('/base')
22 def base():
23     return render_template('index.html')
24 
25 
26 if __name__ == '__main__':
27     app.run()

Bp1.py

 1 '''
 2 flask中的Blueprint蓝图类源码:
 3     def __init__(
 4             self,
 5             name,                   # 唯一蓝图名
 6             import_name,            #当前文件名
 7             static_folder=None,     #静态文件目录
 8             static_url_path=None,   #静态文件请求路径
 9             template_folder=None,   #模板文件目录
10             url_prefix=None,        #url请求路径前缀,如果指定,在请求时必须在端口之后路径之前加上才能正常访问
11             subdomain=None,         #子域
12             url_defaults=None,
13             root_path=None,
14             cli_group=_sentinel,
15         )
16 
17 蓝图中没有config配置和run函数,功能于一个app的分支功能模块,在主程序中通过app.register_blueprint()进行注册引入使用
18 '''
19 
20 from flask import Blueprint, render_template
21 
22 Bp1=Blueprint('Bp1',__name__,static_folder='staticfiles',static_url_path='/static',template_folder='html',url_prefix='/Bp1')
23 
24 @Bp1.route('/BluePrint')
25 def func1():
26     return 'BluePrint1'
27 
28 @Bp1.route('/index')
29 def index():
30     return  render_template('index0.html')

Bp2.py

1 from flask import Blueprint
2 Bp2=Blueprint('Bp2',__name__,url_prefix='/Bp2')
3 
4 @Bp2.route('/BluePrint')
5 def func1():
6     return 'BluePrint2'

indx0.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>index</title>
 6 </head>
 7 <body>
 8 <h2>项目中指定模板文件目录html中的index页面,默认不指定为templates模板目录</h2>
 9 
10 
11 <div><h2>项目中指定静态文件目录staticfiles返回当前图片,默认不指定为static静态文件目录</h2>
12     <img src="/static/1.png" alt=""></div>
13 </body>
14 </html>

 

posted @ 2019-07-11 22:20  笑得好美  阅读(753)  评论(1编辑  收藏  举报