後端

「Flask筆記」 藍圖

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

Recent Posts

Flexible Shipping Pro

在WordPress的世界裡,…

3天 ago

2023 年 WordPress 中最棒的多語言翻譯外掛推薦

擔心如何翻譯您的網站語言以支持…

1年 ago

2023 年 WordPress 中最棒的可視化頁面構建器外掛推薦

在設計任何頁面或網站時,對於不…

1年 ago

Ella 多用途 Shopify 佈景主題

Shopify 佈景主題市場上有許…

1年 ago

AI Engine Pro

喵容今天帶來的 AI Engi…

1年 ago

AIKit

喵容今天為您帶來 AIKit …

1年 ago