flask 应用程序的工厂函数
生活随笔
收集整理的這篇文章主要介紹了
flask 应用程序的工厂函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
隨著flask項(xiàng)目的模塊的越來越多,直接用同一個(gè)應(yīng)用實(shí)例不是一個(gè)很好的選擇,我們把對(duì)象的創(chuàng)建工作移交給一個(gè)函數(shù)來完成,那么你就可以在此后創(chuàng)建它的多個(gè)實(shí)例。
這么做的目的在于:
在我們的視圖模塊注冊(cè)我們的路由(文件/example/views.py)
from flask import Blueprint admin = Blueprint('admin', __name__, url_prefix='/') @admin.route('/', methods=['GET']) def index():return 'hello world'定義一個(gè)應(yīng)用的工廠函數(shù)(文件/example/_init_.py)
from flask import Flask import osdef create_app(config):templates = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'templates'))static = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'static'))app = Flask(__name__, template_folder=templates, static_folder=static)app.config.from_object(config)from example.views import adminapp.register_blueprint(admin)return app最后啟動(dòng)我們的服務(wù)(文件/runserver.py)
from example import create_appapp = create_app('config')if __name__ == '__main__':app.run(debug=True)總結(jié)
以上是生活随笔為你收集整理的flask 应用程序的工厂函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 墨尔本大学 SWEN20003 Proj
- 下一篇: go reflection