flask — 藍圖
使用藍圖
藍圖可以用來將項目分塊,使項目結構更清晰,方便項目管理
#test/blue.py
from flask import Blueprint
test = Blueprint('test',__name__)
@test.route('/test/')
def hello_word():
return 'hello__world'
主app
文件註冊藍圖
from flask import Flask
from test.blue import test
app = Flask(__name__)
app.register_blueprint(test)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
如果希望藍圖下所有網域有個前綴,入/user/test/
可以指定url_prefix
參數
test = Blueprint('test',__name__,url_prefix='/user')
#注意url_prefix後面沒有 / 如果這裡加了 / , 那麼再註冊url的時候前面不要加。即 @app.route('test/')否則路徑會出現兩個 /
藍圖使用範本
普通使用方法和app
下使用的方法一樣
@test.route('/test/')
def hello_word():
return render_template('test.html')
還可以給藍圖指定範本文件的路徑,可以是相對路徑或者絕對路徑
test = Blueprint('test',__name__,url_prefix='/user',template_folder='blup_template')
這兩種方法會優先從template
範本中尋找
藍圖中使用靜態文件
如果使用url_for(‘static’)來加載,那麼就只會在app
制定的靜態文件夾下查找
如果指定藍圖的名字,test.static
,那麼就就再藍圖指定的static_folder
下查找靜態文件
test = Blueprint('test',__name__,url_prefix='/user',static_folder='test_static')
藍圖下url_for
反轉url的注意事項
from flask import Flask,url_for
from sql.blue import test
app = Flask(__name__)
app.register_blueprint(test)
@app.route('/')
def hello_world():
print(url_for('test.hello_word'))
return 'Hello World!'
if __name__ == '__main__':
app.run()
要在反轉url的函式名前添加藍圖名稱
同理再範本文件中反轉url是一致的
子網域的實現
#app.py
from flask import Flask,url_for
from blue.cms import cms
app = Flask(__name__)
app.config['SERVER_NAME'] = 'test.com:5000'
#設置了這個就不能通過127.0.0.1:5000來訪問flask伺服器了
app.register_blueprint(cms)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
from flask import Blueprint
cms = Blueprint('cms',__name__,subdomain='cms')
@cms.route('/')
def index():
return 'cms index'
這樣運行後還不能訪問,因為flask
不支持ip地址
的子網域,需要修改hosts
文件,我這裡把127.0.0.1
映射到test.com
,cms.test.com
這樣cms.test.com
,test.com
都可以成功訪問,實現子網域。