「Flask筆記」 藍圖

「Flask筆記」 藍圖

資源介紹參數
資源類別: Python
如遇問題: 聯繫客服/留言反饋
釋放雙眼,帶上耳機,聽聽看~!

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都可以成功訪問,實現子網域。

聲明:本文為原創作品,版權歸作者所有。未經許可,不得轉載或用於任何商業用途。如若本站內容侵犯了原著者的合法權益,可聯繫我們進行處理。

給TA打賞
共{{data.count}}人
人已打賞
0 條回復 A文章作者 M管理員
    暫無討論,說說你的看法吧